使用Dummy Fake Lock配合std::condition_variable_any是否安全?
Safety of Dummy Fake Locks with
std::condition_variable_any Now to your second question: using a no-op "fake" lock with std::condition_variable_any is technically allowed (since condition_variable_any works with any type that meets the BasicLockable requirement—i.e., has lock() and unlock() methods), but it’s not safe for most real-world use cases.
Here’s why:
- The critical issue is memory visibility and race conditions. Condition variables rely on synchronization to ensure changes to the wait condition (like a "job ready" flag) are visible to waiting threads. A fake lock that does nothing in
lock()/unlock()provides no memory barriers or mutual exclusion, so waiting threads might never see updates to the condition—even after being notified. - Even if you use an atomic condition,
condition_variable_any::waitdepends on the lock’slock()/unlock()calls to enforce proper memory ordering. A no-op lock skips these barriers, leading to undefined behavior (e.g., waiters might stall indefinitely despite the condition being met).
Take this unsafe example:
// UNSAFE EXAMPLE struct FakeLock { void lock() {} void unlock() {} }; FakeLock fake_lock; std::condition_variable_any cv; bool ready = false; // Non-atomic, no synchronization void waiter() { std::unique_lock<FakeLock> lk(fake_lock); while (!ready) { cv.wait(lk); // No memory barriers—ready might never be seen } } void notifier() { std::unique_lock<FakeLock> lk(fake_lock); ready = true; // Race with waiter's condition check cv.notify_one(); }
Even if you make ready atomic, the lack of memory barriers from the fake lock can still cause ordering issues. You could add explicit fences to the fake lock’s methods, but that defeats the purpose of avoiding overhead—and you’re better off just using std::atomic_wait instead.
Summary
- If you can use C++20,
std::atomic_wait/std::atomic_notifyis the standard, lock-free solution you need. - Avoid using dummy fake locks with
std::condition_variable_any—they introduce subtle race conditions and undefined behavior, even if they compile.
内容的提问来源于stack exchange,提问作者xiay
相关产品推荐
相关产品推荐

