[英]Acquire/Release Memory Ordering
In the example: 在示例中:
#include <thread>
#include <atomic>
#include <cassert>
#include <vector>
std::vector<int> data;
std::atomic<int> flag = ATOMIC_VAR_INIT(0);
void thread_1()
{
data.push_back(42);
flag.store(1, std::memory_order_release);
}
void thread_2()
{
int expected=1;
while (!flag.compare_exchange_strong(expected, 2, std::memory_order_acq_rel)) {
expected = 1;
}
}
void thread_3()
{
while (flag.load(std::memory_order_acquire) < 2)
;
assert(data.at(0) == 42); // will never fire
}
int main()
{
std::thread a(thread_1);
std::thread b(thread_2);
std::thread c(thread_3);
a.join(); b.join(); c.join();
}
1- If I replace std::memory_order_acq_rel in thread_2 by std::memory_order_acquire, can I still guarantee that the assertion in thread_3 will never fire? 1-如果我用std :: memory_order_acquire替换thread_2中的std :: memory_order_acq_rel,我还能保证thread_3中的断言永远不会触发吗?
2 - Can std::memory_order_release synchronize with 2 threads using std::memory_order_acquire (if 2 threads are watching over the same flag with acquire semantics)? 2 - std :: memory_order_release可以使用std :: memory_order_acquire与2个线程同步(如果2个线程正在使用获取语义监视同一个标志)?
You have nothing to synchonize-with in thread 2, so std::memory_order_relaxed memory ordering is more rational here. 在线程2中你没有任何东西可以同步 - 所以std :: memory_order_relaxed内存排序在这里更合理。
The std::memory_order_release tagged store of variable x
synchronizes-with std::memory_order_acquire tagged load of variable x
even initial store is followed by sequence of atomic read-modify-write operations on x
在std :: memory_order_release标记变量的存储
x
同步-用的std :: memory_order_acquire标记变量的负载x
甚至初始商店随后在原子读-修改-写操作的序列x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.