#include<atomic>#include<iostream>#include<thread>
std::atomic<charconst*> data;
std::atomic_flag flag = ATOMIC_FLAG_INIT;voidproducer(){// A, Store
data.store("success", std::memory_order_relaxed);// prevents reordering of Store-Store, Load-Store => A happens before B
std::atomic_thread_fence(std::memory_order_release);// B, Store
flag.test_and_set(std::memory_order_relaxed);}voidconsumer(){// C, Load, waits Bwhile(!flag.test(std::memory_order_relaxed));// prevents reordering of Store-Load, Load-Load => C happens before D
std::atomic_thread_fence(std::memory_order_acquire);// D, Load
std::cout << data.load(std::memory_order_relaxed)<<'\n';}/*
* A happens before B
* C waits B
* C happens before D
* therefore, A happends before D
*/intmain(){
std::thread tp{producer};
std::thread tc{consumer};
tp.join();
tc.join();}
댓글 0