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:
- Accepts a maximum number of concurrent workers.
- Provides a
run(taskFunction)method to enqueue tasks. - Executes up to
ntasks concurrently, wherenis the worker limit. - Ensures tasks complete before starting new ones if the limit is reached.
- 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 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
