OSC++.040 explores efficient thread signaling with C++20 std::atomic::wait(), notify_one(), and notify_all(). A worker often needs to pause until another thread publishes a result. Continual polling consumes CPU time and can introduce avoidable scheduling overhead. Following OSC++.039 on cooperative thread shutdown, the new lesson teaches value-based blocking, notification, and memory visibility in portable C++.
Key learning objectives
- Objective 1: Distinguish atomic waiting from busy polling and explain the value-change rule.
- Objective 2: Build and run a signaling example using
waitandnotify_one. - Objective 3: Explain release/acquire ordering and why synchronization protects an ordinary payload.
- Objective 4: Identify missed transitions, limitations, and appropriate alternative primitives.
Objective 1 — Waiting for a value, not a clock
A busy-wait loop repeatedly reads shared state until a condition changes. Polling may be justified for tightly bounded specialized work, but repeated reads can waste processor cycles. In contrast, C++20 atomic.wait(old) compares the atomic object’s value with old. If the values match, the operation can block; it returns only after observing a different value. A notification normally accompanies the producer’s state change. The standard permits spurious unblocking internally, but wait rechecks the comparison before returning. Consult the atomic wait reference and the committee’s C++20 synchronization proposal P1135R6.
Objective 2 — Implement the producer–consumer handshake
A producer publishes one integer payload; the main thread waits for a readiness signal. The atomic variable starts at 0. After preparing the payload, the producer stores 1, then notifies a waiting thread. The consumer asks wait(0) to return only when the observed state differs from the old value. The separate payload deliberately uses an ordinary int; synchronization comes from the atomic state.
#include <atomic>
#include <iostream>
#include <thread>
int main() {
std::atomic<int> state{0};
int payload = 0;
std::jthread producer([&] {
payload = 42;
state.store(1, std::memory_order_release);
state.notify_one();
});
state.wait(0, std::memory_order_acquire);
std::cout << "received: " << payload << '\n';
producer.join();
}
g++ -std=c++20 -Wall -Wextra -Werror -pthread demo.cpp -o demo
./demo
Expected output: received: 42. The example compiled under a C++20-capable GCC toolchain and produced the expected result in thirty consecutive local runs. A signal emitted before the consumer begins waiting is not lost here: after the atomic changes to 1, wait(0) observes a value different from 0 and returns. A notify_one() call without a corresponding value change cannot by itself satisfy the return condition.
Objective 3 — Make the payload visible
Atomicity alone is not the complete memory-ordering story. state.store(1, std::memory_order_release) publishes the producer’s preceding write to payload. The successful state.wait(0, std::memory_order_acquire) observes the new value with acquire semantics. Together, the release/acquire synchronization orders the payload write before the consumer’s later read, preventing a data race in the demonstrated single-publication protocol. A relaxed wait would not provide the same synchronization guarantee. The memory-order reference explains the formal happens-before relationship. OSC++.037 on futures provides another way to communicate results between tasks.
Objective 4 — Recognize edge cases and choose the right tool
Atomic waiting checks a value, not a history of events. If state changes from 0 to 1 and rapidly returns to 0 before the waiter observes it, an intervening transition may be missed: an ABA-style hazard. Use durable state, monotonically advancing sequence numbers with a well-considered wraparound policy, or a queue when every event matters. notify_one is appropriate when one waiting thread should wake; notify_all may serve multiple observers, provided the state transition and protocol support them.
C++20 atomic waiting has no standard timed-wait overload and does not automatically respond to a std::stop_token. A condition variable suits complex predicates and timeouts, while std::condition_variable_any offers stop-token-aware waits. For an owned result and exception propagation, revisit OSC++.038 on async and futures. A move-only callback can instead encapsulate work with explicit ownership. An atomic notification also cannot make unrelated shared objects safe without a sound state protocol.
Knowledge check and worked answers
Check 1: Why is wait(0) better than a tight while(state == 0) loop for a sporadic event? Answer: blocking avoids repeated active polling and permits the implementation to use efficient waiting mechanisms. Check 2: Can a notification alone make wait(0) return while state remains zero? Answer: no. Check 3: Why is the ordinary payload read legal? Answer: release/acquire synchronization orders the producer’s write before the consumer’s read. Check 4: What if every state transition must be recorded? Answer: store durable queued events or use a suitable sequence protocol rather than a single toggling flag.
Engineering takeaway: atomic.wait and notifications coordinate state transitions without a traditional condition-variable mutex for simple protocols, but correct publication, lifetime management, memory ordering, and workload-specific testing remain essential. See OSC++.033 on callables for the lambda-based worker used in the program.
Sources and verification: ISO C++ working-group P1135R6; cppreference atomic wait and memory-order documentation; CppCon 2019 and CppCon 2017 session pages. Local GCC compiled with -Wall -Wextra -Werror -pthread; 30 runs returned 42. Video identity and relevance verified from publisher listings; actual public player playback and mobile viewport behavior require live inspection.
We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.

Educational code only. Use a controlled development environment and test concurrency requirements for each target platform. No production engineering certification or financial recommendation is implied.

Leave a Reply