Using volatile long as an atomic

后端 未结 6 1879
感动是毒
感动是毒 2021-01-13 14:29

If I have something like this...

volatile long something_global = 0;

long some_public_func()
{
    return something_global++;
}

Would it b

6条回答
  •  死守一世寂寞
    2021-01-13 15:12

    No, you must use platform-dependent atomic accesses. There are several libraries that abstract these -- GLib provides portable atomic operations that fall back to mutex locks if necessary, and I believe Boost also provides portable atomics.

    As I recently learned, for truly atomic access, you need a full memory barrier which volatile does not provide. All volatile guarantees is that the memory will be re-read at each access and that accesses to volatile memory will not be reordered. It is possible for the optimizer to re-order some non-volatile access before or after a volatile read/write -- possibly in the middle of your increment! -- so you must use actual atomic operations.

提交回复
热议问题