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

前端 未结 4 1685
野趣味
野趣味 2020-12-06 05:56

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

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 06:48

    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.

提交回复
热议问题