How would you design a C++ thread pool with a protected work queue, condition-variable predicates, orderly shutdown, task-result/exception propagation, and backpressure?
Show answer and explanation
Guard the queue and lifecycle state with one coherent synchronization protocol. Workers wait with a predicate that handles spurious wakeups, remove one task while holding the mutex, then execute it without the lock. Submission must reject work after shutdown begins; packaged_task plus future can transport values and exceptions. Shutdown sets the stop state under the lock, wakes every worker, and joins them, with an explicit contract to drain queued tasks or cancel them. A bounded queue needs backpressure such as blocking, timeout, rejection, or caller-runs behavior so producers cannot consume memory without limit. Define destructor behavior, self-join restrictions, task cancellation, fairness, and failure handling before optimizing contention.
Guard the queue and lifecycle state with one coherent synchronization protocol. Workers wait with a predicate that handles spurious wakeups, remove one task while holding the mutex, then execute it without the lock. Submission must reject work after shutdown begins; packaged_task plus future can transport values and exceptions. Shutdown sets the stop state under the lock, wakes every worker, and joins them, with an explicit contract to drain queued tasks or cancel them. A bounded queue needs backpressure such as blocking, timeout, rejection, or caller-runs behavior so producers cannot consume memory without limit. Define destructor behavior, self-join restrictions, task cancellation, fairness, and failure handling before optimizing contention.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.