Here is a C++17 snippet where one thread waits for another to reach certain stage:
std::condition_variable  cv;
std::atomic<bool>        ready_flag{false};
std::mutex               m;
// thread 1
... // start a thread, then wait for it to reach certain stage
auto lock = std::unique_lock(m);
cv.wait(lock, [&]{ return ready_flag.load(std::memory_order_acquire); });
// thread 2
... // modify state, etc
ready_flag.store(true, std::memory_order_release);
std::lock_guard{m};   // NOTE: this is lock immediately followed by unlock
cv.notify_all();
As I understand this is a valid way to use atomic flag and condition variable to achieve the goal. For example there is no need to use std::memory_order_seq_cst here.
Is it possible to relax this code even further? For example:
- maybe using std::memory_order_relaxedinready_flag.load()
- maybe using std::atomic_thread_fence()instead ofstd::lock_guard{m};
 
     
    