Ste*_*ing 5 c++ multithreading c++11
#include <atomic>
#include <iostream>
#include <thread>
class atomicAcquireRelease00
{
public:
atomicAcquireRelease00() : x(false), y(false), z(0) {}
void run()
{
std::thread a(&atomicAcquireRelease00::write_x, this);
std::thread b(&atomicAcquireRelease00::write_y, this);
std::thread c(&atomicAcquireRelease00::read_x_then_y, this);
std::thread d(&atomicAcquireRelease00::read_y_then_x, this);
a.join();
b.join();
c.join();
d.join();
std::cout<<"z == "<<z.load()<<std::endl;
}
private:
void write_x()
{
x.store(true, std::memory_order_release); //(1)
}
void write_y()
{
y.store(true, std::memory_order_release); //(2)
}
void read_x_then_y()
{
while(!x.load(std::memory_order_acquire)); //(3)
if(y.load(std::memory_order_acquire)){ //(4)
++z;
}
}
void read_y_then_x()
{
while(!y.load(std::memory_order_acquire)); //(5)
if(x.load(std::memory_order_acquire)){ //(6)
++z;
}
}
private:
std::atomic<bool> x, y;
std::atomic<int> z;
};
int main()
{
for(size_t i = 0; i != 50; ++i){
atomicAcquireRelease00().run();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
atomicAcquireRelease00加载值时不要尊重订单.据我所知,如果我将操作存储声明为std::memory_order_release
和操作加载std::memory_order_acquire一对,则在同一个原子变量上加载和存储的操作将同步,但是这个简单的例子不能像我预期的那样工作.
这个过程基于我的想象力
案例A:
案例B:
案例C:
我不能保证x或者y首先将其设置为true,但是当x设置为true时,x应该将负载与其同步,以及y,什么样的情况会z保持为零?
这正是 Anthony Williams的"Concurrency In Action"中的示例清单5.7.
他解释说:
在这种情况下,断言可以触发(就像在宽松排序的情况下一样),因为读取的负载
x和负载都是y可能的false.x和y由不同的线程写入,因此在每种情况下从发布到获取的排序对其他线程中的操作没有影响.
