Multithreading – Difference Between Atomic Operation and Thread Safety

cmultithreadingprogramming-languages

From the discussion I've seen it seems that atomic operation and thread safety are the same thing, but a lot of people say that they're different. Can anyone tell me the difference if there is one?

Best Answer

Atomic operations are a way to achive thread safety either by using some kind of locks like Mutexes or Semaphores which use atomic operations internally or by implementing lock free synchronization using atomics and memory fences.

So atomic operations on primitive data types are a tool to achive thread safety but do not ensure thread safety automatically because you normally have multiple operations that rely on each other. You have to ensure that these operations are done without interruption eg using Mutexes.

Yes, writing one of these atomic data types in c# is thread safe, but that does not make the function you use them in thread safe. It only ensures that the single write is correctly executed even if a second thread accesses it "at the same time". Never the less, the next read from the current thread is not ensured to get the value previously written as a different thread might have written to it, only that the value read is valid.

Related Topic