Talk:cpp/atomic/atomic/wait
[edit] Race Condition in Example
I'm pretty sure the example for std::atomic<T>::wait has a race condition. Specifically, it's (in theory) possible for an async task to decrement outstanding_task_count and find it equal to zero (and therefore call the notify_one() too early) before the next iteration of the task-spawner increments outstanding_task_count. In other words, outstanding_task_count could reach zero before completion_count reaches 16 (and therefore, all tasks would not be completed when the wait returns).
One way to trigger this race condition is to remove the sleep and increasing the task count. When I run it enough times (latest clang or gcc), it prints an inconsistent number of completed tasks.
I couldn't edit the page to fix the example, but here's one way to fix it without changing the intent too much:
Instead of incrementing outstanding_task_count immediately before we spawn each task, set outstanding_task_count at the very beginning to the number of tasks we have to complete. Something like:
outstanding_task_count = std::extent_v<decltype(task_futures)>;