1
votes

I heard that a single atomic operation is thread-safe because when a core is processing an atomic operation the core wouldn't be doing anything else before it completes that atomic operation .

for example in java in a 32 bit operating system say there is a variable accessible to multiple Threads

 int a; 

thread 1 write in a

a = 3; 

and thread 2 can write

a = 4; 

the order of the threads writing to that variable may change so the final value can either be 3 or 4 but we can be sure that writing to an int is an atomic operation so the 32 bits in that variable won't be mixed up in to some unpredictable number

I get that this is the case in a single core environment since the core would not be executing a code of another thread before it is sure that the atomic operation is complete,

however in a multi core environment isn't it possible that another core accesses the variable that is under an atomic operation of the current core? thus causing the 32bits in the variable to get mixed up?

2

2 Answers

6
votes

No - that's what atomic means: the write will always succeed "without interference". So you will either read 0 (the original value), 3 or 4 but no other value.

What will happen in a multi core setting is that if thread T1 writes 3 on core C1 and thread T2 writes 4 on core C2, the value may remain visible only to the core that made the write. So your int may have a value of 3 in C1 and 4 in C2 at the same time. And if there is a third core C3, it may still see the original value of 0.

To prevent that inconsistency, you need to add some synchronization (for example by making the int volatile).

1
votes

In short, none of example operations are thread safe. You need to use atomics or synchronization to grantee any predictable output. In the given example it is even possible that on reading thread 'a' will endup as 0 and will nether be updated to '3' or '4'.

Atomics are not just about atomicity, they are also about ordering. And the latter is the cornerstone of all concurrent programming.

Keep in mind that there are many things, which can go wrong and it is not only what is going on in the CPU. Compiler also reorder operations or even eliminate main memory writes.

I would recommend reading the following links to understand how all that stuff works: