I am reading about atomicity and came across the following scenario

int x = y = z = 0;

Thread 1        Thread 2
---------       --------
x = y + z       y = 1
                z = 2

Which gives the following sets of output

$$\begin{array}{ccc}1&2&3\\ T1 : x = y + z&T2 : y = 1&T2 : y = 1\\T2 : y = 1&T2 : z = 2&T1 : x = y + z\\T2 : z = 2&T1 : x = y + z&T2 : z = 2\end{array}$$

Translating the $x=y+z$ expression to machine code gives

load r1; y
load r2; z
add r3; r1; r2
store r3; 

However according to some notes I read going down the path of

T1 : load r1, y
T2 : y = 1
     z = 2
T1 : load r2, z
     add r3, r1, r         
     store r3, x

I cannot seem to understand how the author came to result that $x=2$.

To me, based on the previous machine instructions the result should be 3, which I guess leads me to realize I am supposed to hit eureka (or a simple misread) and realize where the atomicity occurs. Could you explain the atomicity in this fairly simple statement that leads to the correct result?

  • $\begingroup$ I guess y is defined before the assignment so it takes 0 for r1 and therefore x would be 2. But I'm not sure as it's an assembly code which I don't know much about. $\endgroup$
    – Gigili
    Commented Mar 13, 2012 at 17:13

1 Answer 1


The point you are missing is that in thread $y$ is loaded into $r1$ and that any subsequent changes to $y$ will not affect the value stored in $r1$. Thus, the value in $r1$ is $0$ even after statement $y=1$. From this it is easy to see that the result is $x=2$.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.