Implementing a thread-safe shutdown mechanism in C++17
This easy coding problem asks you to build a minimal synchronisation primitive for coordinating thread shutdown across C++17 code. It tests whether you understand how to share mutable state safely between threads without reaching for a mutex — a constraint that forces you to think about lock-free or atomic patterns.
The core challenge is designing two linked classes: a stop_source that signals shutdown, and a stop_token that multiple threads check to know when to exit their work loops. Since a single source can distribute copies of the same token to many threads, the token must reference shared state that remains consistent and thread-safe even as threads query it concurrently. Without mutexes, you will need to rely on atomic operations to manage that state correctly.
- Atomic variables and memory ordering semantics
- Shared ownership and lifetime of synchronisation state
- Copy semantics for tokens across thread boundaries
- Safe shutdown signalling without blocking
The test cases will verify that your implementation correctly prevents data races, allows multiple threads to safely read the stop state, and properly propagates the shutdown signal from source to all token holders.