Are primitive data types in c# atomic (thread safe)?

Benny picture Benny · Mar 12, 2010 · Viewed 14.1k times · Source

For example, do I need to lock a bool value when multithreading?

Answer

Aaronaught picture Aaronaught · Mar 12, 2010

There is no such thing as an atomic type. Only operations can be atomic.

Reading and writing a data type that fits into a single word (int on a 32-bit processor, long on a 64-bit processor) is technically "atomic", but the jitter and/or processor can decide to reorder instructions and thus create unexpected race conditions, so you either need to serialize access with lock, use the Interlocked class for writes (and in some cases reads), or declare the variable volatile.

The short answer is: If two different threads may access the same field/variable and at least one of them will be writing, you need to use some sort of locking. For primitive types that's generally the Interlocked class.