Facebook Pixel

Worker Pool

JavaScript
hard
30 mins

A Worker Pool manages multiple worker threads to process tasks concurrently while limiting the number of workers running at the same time. Implement a WorkerPool class that:

  1. Accepts a maximum number of concurrent workers.
  2. Provides a run(taskFunction) method to enqueue tasks.
  3. Executes up to n tasks concurrently, where n is the worker limit.
  4. Ensures tasks complete before starting new ones if the limit is reached.
  5. Returns a promise that resolves with the task's result once completed.

Example Inputs & Outputs

const pool = new WorkerPool(2); // Max 2 concurrent workers async function task(id, delay) { return new Promise(resolve => setTimeout(() => resolve(`Task ${id} done`), delay)); } // Run tasks pool.run(() => task(1, 1000)).then(console.log); // Task 1 done (after 1s) pool.run(() => task(2, 500)).then(console.log); // Task 2 done (after 0.5s) pool.run(() => task(3, 200)).then(console.log); // Task 3 waits for a slot // Output (timing may vary): // Task 2 done // Task 1 done // Task 3 done

Constraints & Edge Cases

  • 1 ≤ maxWorkers ≤ 10⁴
  • Tasks can have different execution times.
  • Tasks should be executed in FIFO order when slots become available.
  • If all workers are busy, new tasks should wait in a queue.
  • Edge Cases:
    • Running with maxWorkers = 1 (sequential execution).
    • Handling tasks that fail (errors should not break the pool).
    • Ensuring Promise-based execution.

Companies:

stripe
dropbox
meesho

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.