Are reference assignment and reading atomic operations?

前端 未结 1 1314
不知归路
不知归路 2021-02-07 09:53

I have found several questions about this same topic but related to general variables (value and reference types) The accepted answer from this question says:

Partition

1条回答
  •  一生所求
    2021-02-07 10:34

    Yes, everything is guaranteed to be properly aligned unless you deliberately go out of your way to misalign stuff, meaning that reference assignment/reading is guaranteed to be atomic.

    Section 12.6.6 of the CLI spec goes on to say this:

    Unless explicit layout control (see Partition II (Controlling Instance Layout)) is used to alter the default behavior, data elements no larger than the natural word size (the size of a native int) shall be properly aligned. Object references shall be treated as though they are stored in the native word size.

    There are also further details about alignment etc in section 12.6.2 of the spec.

    Note that in your example code, the read in thread 2 is guaranteed to be atomic, but it's not guaranteed to actually see any changes made by thread 1: without enforcing memory barriers or volatility each thread can use its own "view" of the m_Object field without ever seeing changes made by other threads.

    So, for example, thread 1 could be making (atomic) writes into its own view of m_Object, but the data is only ever actually held in a register or CPU cache and never comitted to main memory. Similarly, thread 2 could also be making (atomic) reads of m_Object, but actually reading from a register or CPU cache rather than main memory.

    0 讨论(0)
提交回复
热议问题