为什么 c++11 memory_order_relaxed 仍然导致顺序等待?
Why c++11 memory_order_relaxed still leads to sequencial wait?
我希望原子加载不必等待赋值,但我在下面的代码中:
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
atomic<bool> y;
void write()
{
this_thread::sleep_for(chrono::seconds(2));
cout<<"end sleep\n";
y.store(true,memory_order_relaxed);
}
void read()
{
while(!y.load(memory_order_relaxed));
cout<<"end load\n";
}
int main() {
y = false;
thread a(write);
thread b(read);
a.join();
b.join();
cout<<y.load()<<endl;
}
main会执行,等待2秒,然后打印:
end sleep
end load
1
我运行重复了很多次,结果总是一样。
所以在我看来 "read()" 函数的 "atomic_load" 将等待 "write()" 函数的 "store" 完成。这是我程序的问题,还是c++11内存顺序的设计问题?
我在 ubuntu18.04 和 g++ 上。谢谢
您的 read
函数有一个 while
循环,该循环会一直重复,直到 y.load()
读取的值不为零。因此,这将循环直到 1 到 y
的存储对该线程可见。
在 main
打印之前对 join
的调用确保两个线程都已完成,因此 1 到 y
的存储也在打印之前完成。
我希望原子加载不必等待赋值,但我在下面的代码中:
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
atomic<bool> y;
void write()
{
this_thread::sleep_for(chrono::seconds(2));
cout<<"end sleep\n";
y.store(true,memory_order_relaxed);
}
void read()
{
while(!y.load(memory_order_relaxed));
cout<<"end load\n";
}
int main() {
y = false;
thread a(write);
thread b(read);
a.join();
b.join();
cout<<y.load()<<endl;
}
main会执行,等待2秒,然后打印:
end sleep
end load
1
我运行重复了很多次,结果总是一样。
所以在我看来 "read()" 函数的 "atomic_load" 将等待 "write()" 函数的 "store" 完成。这是我程序的问题,还是c++11内存顺序的设计问题?
我在 ubuntu18.04 和 g++ 上。谢谢
您的 read
函数有一个 while
循环,该循环会一直重复,直到 y.load()
读取的值不为零。因此,这将循环直到 1 到 y
的存储对该线程可见。
在 main
打印之前对 join
的调用确保两个线程都已完成,因此 1 到 y
的存储也在打印之前完成。