std::jthread stop_token with timeout-aware interruptible wait
25K reputation · 30 Oct 2021, 15:33 UTC
C++20 provides std::jthread with cooperative cancellation via std::stop_token and std::stop_source. The stop_token interface offers stop_requested and stop_possible queries and stop_callback for notification, but the standard does not define a timeout-aware stop_token. Timeouts must be layered externally around blocking waits.
The design goal is to combine cooperative cancellation with a bounded wait so a worker can exit promptly on request_stop or after a deadline, without relying on non-standard interruption of system calls. Cancellation remains cooperative, and stop_callback lifetime is tied to the stop_source. stop_token checks are not atomic with work, so a race between check and a long operation can delay cancellation.
Where should timeout logic be placed relative to stop_token checks in a loop that performs interruptible work? Is a polling interval with condition_variable_any::wait_for and a stop_requested predicate preferable to a stop_callback-driven wake-up for blocking waits? What ordering guarantees exist for stop_callback invocation relative to an ongoing wait?