Is volatile a proper way to make a single byte atomic in C/C++?

后端 未结 5 887
渐次进展
渐次进展 2021-01-04 10:25

I know that volatile does not enforce atomicity on int for example, but does it if you access a single byte? The semantics require that writes and reads are always from memo

5条回答
  •  一整个雨季
    2021-01-04 11:05

    Short answer : Don't use volatile to guarantee atomicity.

    Long answer One might think that since CPUs handle words in a single instruction, simple word operations are inherently thread safe. The idea of using volatile is to then ensure that the compiler makes no assumptions about the value contained in the shared variable.

    On modern multi-processor machines, this assumption is wrong. Given that different processor cores will normally have their own cache, circumstances might arise where reads and writes to main memory are reordered and your code ends up not behaving as expected.

    For this reason always use locks such as mutexes or critical sections when access memory shared between threads. They are surprisingly cheap when there is no contention (normally have no need to make a system call) and they will do the right thing.

    Typically they will prevent out of order reads and writes by calling a Data Memory Barrier (DMB on ARM) instruction which guarantee that the reads and writes happen in the right order. Look here for more detail.

    The other problem with volatile is that it will prevent the compiler from making optimizations even when perfectly ok to do so.

提交回复
热议问题