Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Similar Question here

For the definitive answer go to the spec. :)

Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size."

So that confirms that s_Initialized will never be unstable, and that read and writes to primitve types are atomic.

Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example.

John.

Essentially, you wont have a "crash" problem from not locking a bool. What you may have is a race condition for the order of which the bool is updated or read. If you want to garuntee that the bool is written to/read from in a specific order, then you'd want to use some sort of locking mechanism.

Sort of. There's an excellent thread about this here, but the short version is, while a given read or write may be atomic, that's almost never what you're doing. For example, if you want to increment an integer, you need to 1) read the value, 2) add one to the value and 3) store the value back. Any of those operations can be interrupted.

That's the reason for classes such as "Interlocked".

Static primitive types are threadsafe, so you don't need to lock those typed variables. However, any instance variable of a primitive type is not guaranteed to be. See here: Are primitive types like bool threadsafe ?

MSDN PrimitiveType Class

And here's another useful link that might also be of interest which I find the solution very compelling: SO Question: How do I know if a C# method is thread safe?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top