Medium
Nested submission to a fixed-size thread pool
A thread pool has exactly 2 worker threads. Both workers are simultaneously given a task of the shape shown: the task itself calls pool.submit() to enqueue a new task on the same pool, then calls .get() on the resulting future to synchronously wait for that new task's result before returning. What happens?
main.cpp
class ThreadPool {
public:
ThreadPool(size_t n); // spawns n worker threads, each looping: pull job from queue, run it
std::future<int> submit(std::function<int()> job); // enqueues job, wakes a worker, returns its future
// ...
};
ThreadPool pool(2); // exactly 2 worker threads
auto f1 = pool.submit([&pool] {
auto inner = pool.submit([] { return 1; }); // enqueue a second task on the SAME pool
return inner.get(); // block this worker until it completes
});
auto f2 = pool.submit([&pool] {
auto inner = pool.submit([] { return 2; });
return inner.get();
});
f1.get(); // caller waits for the outer tasks
f2.get();35 of 51 in Concurrency