My book presents a simple example which I'm a bit confused about:

It says, "consider the following program, and assume that the fine-grained atomic actions are reading and writing the variables:"

int y = 0, z = 0;
co x = y+z; // y=1; z=2; oc;

"If x = y + z is implemented by loading a register with y and then adding z to it, the final value of x can be 0,1,2, or 3. "

2? How does 2 work?

Note: co starts a concurrent process and // denote parallel-running statements

有帮助吗?

解决方案

In your program there are two parallel sequences:

Sequence 1: x = y+z;

Sequence 2: y=1; z=2;

The operations of sequence 1 are:

  1. y Copy the value of y into a register.
  2. + z Add the value of z to the value in the register.
  3. x = Copy the value of the register into x.

The operations of sequence 2 are:

  1. y=1; Set the value of y to 1.
  2. z=2; Set the value of z to 2.

These two sequences are running at the same time, though the steps within a sequence must occur in order. Therefore, you can get an x value of '2' in the following sequence:

  1. y=0
  2. z=0
  3. y Copy the value of y into a register. (register value is now '0')
  4. y=1; Set the value of y to 1. (has no effect on the result, we've already copied y to the register)
  5. z=2; Set the value of z to 2.
  6. + z Add the value of z to the value in the register. (register value is now '2')
  7. x = Copy the value of the register into x. (the value of x is now '2')

其他提示

Since they are assumed to run in parallel, I think an even simpler case could be y=0, z=2 when the assignment x = y + z occurs.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top