问题描述
在c ++ 11中,可以使用std :: atomic在两个线程之间传输非原子数据?详细来说,以下4个语义是否都由原子建立?
In c++11, can std::atomic be used to transmit non-atomic data between two thread? In detail, are the following 4 semantics all established by atomic?
-
所有语句(当谈论执行时,包括所有机器指令
all statements(when talking about execution, including all machine instructions generated by those c++ statements) before an atomic-write statement are executed before the atomic-write.
所有语句(当谈论执行时,包括所有机器指令
all statements(when talking about execution, including all machine instructions generated by those c++ statements) after an atomic-read are executed after the atomic-read.
所有其他内存写入在写入一个原子之前被提交到main
all other memory-write before writing an atomic are committed to main memory.
所有其他内存读取在读取原子后将从主内存中再次读取(意味着丢弃线程缓存)。
all other memory-read after reading an atomic will read from main memory again(that means discard thread cache).
我在这里看到一个例子:
I have seen an example here: http://bartoszmilewski.com/2008/12/01/c-atomics-and-memory-ordering/
但是,在这个例子中,数据是一个原子,所以我的问题是,如果数据是非原子的?
However, in the example, the data is an atomic, so my question is, what if the data is non-atomic?
代码,显示我想要的内容:
Here is some code, showing what i want:
常用数据:
std::atomic_bool ready;
char* data; // or data of any other non atomic
写线程:
data = new char[100];
data[0] = 1;
ready.store(true); // use default memory_order(memory_order_seq_cst), witch i think is the most restrict one
/ p>
read thread:
if(ready.load()) { // use default memory_order(memory_order_seq_cst)
assert(data[0] == 1); // both data(of type char*) and data[0~99](each of type char) are loaded
}
推荐答案
我认为你必须使用内存订单:
I think you must use memory orders:
data = new char[100];
data[0] = 1;
ready.store_explicit(true, std::memory_order_release);
if(ready.load_explicit(std::memory_order_aqcuire)) {
assert(data[0] == 1); // both data(of type char*) and data[0~99](each of type char) are loaded
}
(我不确定这个语法 _explicit
)
是正确的,但在这种情况下,不需要sec / cst内存顺序,获取/释放
是正确的。
with release
没有写入可以在原子写入之后重新排序,并且获取
加载,所以原子存储之前的所有非原子存储将在原子加载后对所有加载可见。
Actually your code is correct, but in this case there is no need to sec/cst memory order and acquire/release
is correct.with release
no write can be reordered after atomic write and with acquire
no load can be reordered before atomic load, so all non-atomic store before atomic store will be visible to all loads after atomic load.
这篇关于在c ++ 11中,可以使用std :: atomic在两个线程之间传输非原子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!