Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 672
Benny Avatar asked Mar 12 '10 15:03

Benny


1 Answers

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.

like image 70
Aaronaught Avatar answered Oct 05 '22 19:10

Aaronaught