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

后端 未结 5 921
渐次进展
渐次进展 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 10:46

    Not only does the standard not say anything about atomicity, but you are likely even asking the wrong question.

    CPUs typically read and write single bytes atomically. The problem comes because when you have multiple cores, not all cores will see the byte as having been written at the same time. In fact, it might be quite some time (in CPU speak, thousands or millions of instructions (aka, microseconds or maybe milliseconds)) before all cores have seen the write.

    So, you need the somewhat misnamed C++0x atomic operations. They use CPU instructions that ensure the order of things doesn't get messed up, and that when other cores look at the value you've written after you've written it, they see the new value, not the old one. Their job is not so much atomicity of operations exactly, but making sure the appropriate synchronization steps also happen.

提交回复
热议问题