Search code examples
multithreadingconcurrencyshared-memoryimperative-programming

Stuck on a Concurrent programming example, in pseudocode(atomic actions/fine-grained atomicity)


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


Solution

  • 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')