Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

c++11 - C++ memory model and race conditions on char arrays

Basically I have trouble understanding this: (from Bjarne FAQ)

However, most modern processors cannot read or write a single character, it must read or write a whole word, so the assignment to c really is ``read the word containing c, replace the c part, and write the word back again.'' Since the assignment to b is similar, there are plenty of opportunities for the two threads to clobber each other even though the threads do not (according to their source text) share data!

So how can char arrays exist without 3(7?) byte padding between elements?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...