For example, do I need to lock a bool
value when multithreading?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With