标准原子同步和非原子变量:不是陈旧数据?
std atomic synchronisation and non atomic variable : not a stale data?
我知道这段代码是正确的(除了 delete
没有完成):
#include <thread>
#include <atomic>
#include <cassert>
#include <string>
std::atomic<std::string*> ptr;
int data;
void producer()
{
std::string* p = new std::string("Hello");
data = 42;
ptr.store(p, std::memory_order_release);
}
void consumer()
{
std::string* p2;
while (!(p2 = ptr.load(std::memory_order_acquire)))
;
assert(*p2 == "Hello"); // never fires
assert(data == 42); // never fires
}
int main()
{
std::thread t1(producer);
std::thread t2(consumer);
t1.join(); t2.join();
}
但是,我想知道为什么在消费者线程中数据不能是陈旧数据。是因为acquire
操作吗?
分配给data
happens-beforeptr.store
调用。访问 data
发生在 该调用之后(是的,通过与原子对象同步)。因此,可以保证访问看到先前分配的值。
我知道这段代码是正确的(除了 delete
没有完成):
#include <thread>
#include <atomic>
#include <cassert>
#include <string>
std::atomic<std::string*> ptr;
int data;
void producer()
{
std::string* p = new std::string("Hello");
data = 42;
ptr.store(p, std::memory_order_release);
}
void consumer()
{
std::string* p2;
while (!(p2 = ptr.load(std::memory_order_acquire)))
;
assert(*p2 == "Hello"); // never fires
assert(data == 42); // never fires
}
int main()
{
std::thread t1(producer);
std::thread t2(consumer);
t1.join(); t2.join();
}
但是,我想知道为什么在消费者线程中数据不能是陈旧数据。是因为acquire
操作吗?
分配给data
happens-beforeptr.store
调用。访问 data
发生在 该调用之后(是的,通过与原子对象同步)。因此,可以保证访问看到先前分配的值。