Atomicity of the simple assignment operator

后端 未结 1 1420
深忆病人
深忆病人 2021-01-12 14:56

C11 Standard says that for atomic types (_Atomic), prefix and postfix ++ and -- operations are atomic (6.5.2.4.,p2), as are compound assignments: <

1条回答
  •  抹茶落季
    2021-01-12 15:36

    Following the example in this Dr Dobbs article, simple assignment of atomic variables in C11 is atomic.

    The C11 standard (ISO/IEC 9899:2011), section 6.2.6.1/9 reads:

    Loads and stores of objects with atomic types are done with memory_order_seq_cst semantics.

    In addition to being atomic, operations performed with memory_order_seq_cst semantics have a single ordering observed by all threads (aka sequentially-consistent ordering).

    Without the _Atomic type qualifier, it is possible for an assignment to be non-atomic. Assigning a 64 bit value (e.g. a long long) on a 32 bit machine requires two CPU cycles. If another thread reads the value between those two cycles they'll get 4 bytes of the old value and 4 bytes of the new value.

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