char数组上的C ++内存模型和竞争条件 [英] C++ memory model and race conditions on char arrays

查看:93
本文介绍了char数组上的C ++内存模型和竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我很难理解这一点:(来自Bjarne FAQ)

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


但是,大多数现代处理器无法读取或写入单个
字符,它必须读取或写入整个单词,因此对c
的赋值实际上是``读取包含c的单词,替换c部分,然后再次将
单词写回去。''由于对b的分配是相似的,因此
的两个线程有​​很多机会互相破坏甚至
,尽管线程不(根据其源文本)共享数据!

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!

那么在元素之间没有3(7?)个字节填充的情况下,char数组如何存在?

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

推荐答案

我认为Bjarne对此是错误的,或者至少,他是
可以大大简化事情。大多数现代处理器
能够写一个字节而不必先读一个完整的单词,甚至
,它们的行为好像就是这种情况。特别是在
中,如果您有一个 char数组[2]; ,并且只有一个线程
访问 array [0] 和线程两个仅访问 array [1]
(包括当两个线程都在改变值时),然后
不需要不需要任何其他同步;这由标准保证
。如果硬件不允许直接这样做,则
编译器将不得不自己添加同步。

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.

这篇关于char数组上的C ++内存模型和竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆