AlgoMaster Logo
AlgoMasterDesign a Thread Poolhard

Design a Thread Pool

hard

Design a fixed-size thread pool that accepts callbacks and executes them using a bounded number of long-lived worker threads.

Implement the ThreadPool class:

  • ThreadPool(workerCount) starts exactly workerCount worker threads. Workers wait when no work is available and may be reused for later tasks.
  • submit(task) atomically accepts a task while the pool is running and returns true. An accepted task must execute exactly once on a worker thread. After shutdown begins, it rejects the task and returns false.
  • shutdown() stops accepting new tasks, executes every previously accepted task, waits for all workers to exit, and then returns.

submit may be called concurrently by many threads. shutdown is idempotent and may also be called concurrently: every caller must wait until all accepted tasks have finished.

Callbacks must run outside the pool's internal lock. A callback may therefore submit another task to the same pool while the pool is still accepting work. A task must never be executed inline by the thread calling submit.

The judge creates the callbacks and calls shutdown; your implementation should provide only the thread-pool synchronization. The judge also preloads the standard concurrency, callback, thread, and collection APIs for every supported language. You do not need to add import, include, or using statements.

Example 1:

Input:

Output:

Explanation: Both tasks are accepted and finish before shutdown returns. BA is also a valid output because task order is not guaranteed.

Example 2:

Input:

Output:

Explanation: The first submission returns true. The submission after shutdown returns false, so its callback is never executed.

Constraints

  • 1 <= workerCount <= 16
  • At most 2,000 tasks are submitted.
  • Calls to submit and shutdown may be concurrent.
  • Accepted tasks may execute in any order.
  • Judge callbacks finish in finite time and do not throw exceptions.
  • Judge callbacks never call shutdown from a worker thread.
Loading...

Input

pool = ThreadPool(2)
pool.submit(() => print("A"))
pool.submit(() => print("B"))
pool.shutdown()

Output

AB

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.