liveBook · Manning

Interruptible wait

As explained in C++ Concurrency in Action, Second Edition

A blocking wait operation that returns control when the waiting thread is interrupted.

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

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Builds condition-variable waits around flag registration, notification, cleanup, and interruption checks; uses timed polling for other waits.
Examples
Uses a predicate-based condition-variable loop and short timed waits on a future.
What it assumes
Assumes an interrupt flag, interruption-point mechanism, and synchronization primitives rather than teaching them from zero.
What you can do after
Apply interruption checks and timed polling to condition-variable and future waits, balancing response delay against wake-up overhead.
How it connects
Connects thread interruption with interruption points, condition variables, futures, mutex locks, and timed waits.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.