I expect that atomic load will not have to wait for value assignment, but I've below code:
#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;
}
The main will execute, wait for 2 seconds, and then print:
end sleep
end load
1
I ran it many times, and always the same result.
So it seems to me that the "read()" function's "atomic_load" will wait for "write()" function's "store" to finish. Is this a problem of my program, or the design of c++11 memory order?
I'm on ubuntu18.04 and g++. Thanks.
Aucun commentaire:
Enregistrer un commentaire