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

a 夏天 提交于 2019-12-17 16:29:35

问题


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


回答1:


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.




回答2:


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".




回答3:


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.




回答4:


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?



来源:https://stackoverflow.com/questions/2433772/are-primitive-data-types-in-c-sharp-atomic-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!