[英]in c++11, can std::atomic be used to transmit non-atomic data between two thread
In c++11, can std::atomic be used to transmit non-atomic data between two thread? 在c ++ 11中,可以使用std :: atomic在两个线程之间传输非原子数据吗? In detail, are the following 4 semantics all established by atomic?
详细地说,以下4种语义是否都是由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. 原子写语句之前的所有语句(谈论执行时,包括那些c ++语句生成的所有机器指令)都在原子写之前执行。
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. 原子读取之后的所有语句(在谈论执行时,包括那些c ++语句生成的所有机器指令)都在原子读取之后执行。
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/ 我在这里看到了一个例子: 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: 这是一些代码,显示我想要的:
common data: 常用数据:
std::atomic_bool ready;
char* data; // or data of any other non atomic
write thread: 写线程:
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
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
}
(i am not sure about this syntax _explicit
) (我不确定
_explicit
语法)
Actually your code is correct, but in this case there is no need to sec/cst memory order and acquire/release
is correct. 实际上,您的代码是正确的,但是在这种情况下,不需要sec / cst内存顺序并且
acquire/release
是正确的。 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. 具有
release
用户在原子写操作之后不能对所有写操作进行重新排序,而没有acquire
加载可以在原子加载之前进行重新排序,因此原子存储之后所有加载都可以看到原子存储之前的所有非原子存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.