An interruptible wait turns a blocking operation into one that can return control when the waiting thread is interrupted. For a condition variable, the interrupting thread sets the flag and notifies waiters; the waiting thread checks for interruption after waking. section 9.2.3 section 9.3
A condition-variable wait needs to coordinate interruption with the wait itself:
- Check for interruption, associate the condition variable with the thread’s interrupt flag, then wait and clear the association. section 9.2.3
- Use cleanup that runs if the wait throws: otherwise the association may remain set. Notifying all waiters can wake unrelated threads, which must tolerate spurious wake-ups. section 9.2.3
template<typename Predicate>
void interruptible_wait(std::condition_variable& cv,
std::unique_lock<std::mutex>& lk,
Predicate pred)
{
interruption_point();
this_thread_interrupt_flag.set_condition_variable(cv);
interrupt_flag::clear_cv_on_destruct guard;
while(!this_thread_interrupt_flag.is_set() && !pred())
{
cv.wait_for(lk,std::chrono::milliseconds(1));
}
interruption_point();
}
This condition-variable pattern checks both the interrupt flag and a predicate, waiting in short intervals before checking for interruption again. section 9.2.3
Waiting for a future
A future can be polled with short timed waits until it is ready or interruption is requested. Shorter intervals may reduce response delay but increase wake-ups and task-switching overhead; actual timing depends on clock resolution. section 9.2.5
