C++ memory model and race conditions on char arrays

依然范特西╮ 提交于 2019-11-27 23:15:54

I think Bjarne is wrong about this, or at least, he's simplifying things considerably. Most modern processors are capable of writing a byte without reading a complete word first, or rather, they behave "as if" this were the case. In particular, if you have a char array[2];, and thread one only accesses array[0] and thread two only accesses array[1] (including when both threads are mutating the value), then you do not need any additional synchronization; this is guaranteed by the standard. If the hardware does not allow this directly, the compiler will have to add the synchronization itself.

It's very important to note the "as if", above. Modern hardware does access main memory by cache lines, not bytes. But it also has provisions for modifying single bytes in a cache line, so that when writing back, the processor core will not modify bytes that have not been modified in its cache.

A platform that supports C++11 must be able to access storage of the size of one char without inventing writes. x86 does indeed have that ability. If a processor must modify 32 bits at once at any time, it must have a 32-bit wide char.

(Some background reasoning: arrays are stored contiguously, and chars have no padding (3.9.1).)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!