libstdc++: Fix missed atomic notifying operations [PR127757]
Corrects missed wake-ups in C++20 atomics by adding a full memory fence to prevent race conditions.
This commit fixes a race condition in C++20’s atomic wait/notify operations where the notifier thread might incorrectly believe there are no waiters. This could lead to missed wake-ups because the futex syscall is elided. A seq_cst ordered full fence has been added to __waitable_state::_M_waiting to ensure that either the waiter observes the updated atomic state or the notifier correctly detects waiting threads, preventing missed notifications.
In Details
The __waitable_state::_M_waiting function, responsible for handling atomic waits, previously lacked sufficient memory ordering guarantees. A race existed where a notifying thread could observe _M_waiters == 0 after a waiting thread had already decremented it but before the waiting thread completed its state update and entered the futex wait. This commit introduces a std::atomic_thread_fence(memory_order_seq_cst) to synchronize these operations, ensuring that the notifier either sees a non-zero waiter count or the waiter correctly proceeds to block.
- Atomic operations
- Operations on data that are guaranteed to execute indivisibly, preventing interference from other threads.
- futex
- Fast Userspace muTex, a Linux kernel mechanism used to implement mutexes and condition variables efficiently by combining userspace and kernel operations.
- Memory fence
- An instruction that enforces ordering constraints on memory operations, ensuring that memory accesses before the fence are completed before accesses after the fence.
- seq_cst ordering
- The strongest memory ordering guarantee, 'sequentially consistent', which ensures that all threads observe atomic operations in the same total order.
- C++20 atomics
- The C++20 standard's additions and modifications to atomic types and operations, including support for condition variables via atomic objects.