CodeFree/6_solution/memory_order/2_释放获取顺序.cpp

40 lines
1.3 KiB
C++
Raw Permalink Normal View History

2024-12-26 13:57:27 +08:00
/*
* 线 A memory_order_release 线 B memory_order_acquire
* 线 A 线 B 线 B 线 A
*
* 线线线访
*
* std::mutex 线 A 线 B 线 A 线 B
*
*/
#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"); //绝无问题
assert(data == 42); //绝无问题
}
int main()
{
std::thread t1(producer);
std::thread t2(consumer);
t1.join(); t2.join();
}