Bird
0
0

Given this simplified worker pool code snippet, what will be logged to the console?

medium📝 component behavior Q13 of 15
Node.js - Worker Threads
Given this simplified worker pool code snippet, what will be logged to the console?
const { Worker } = require('worker_threads');

class WorkerPool {
  constructor(size) {
    this.workers = Array(size).fill(null).map(() => new Worker('./worker.js'));
  }
  runTask(task) {
    return new Promise((resolve) => {
      const worker = this.workers.pop();
      worker.once('message', (result) => {
        this.workers.push(worker);
        resolve(result);
      });
      worker.postMessage(task);
    });
  }
}

const pool = new WorkerPool(2);
pool.runTask('task1').then(console.log);
pool.runTask('task2').then(console.log);
ARuns tasks sequentially, logs task1 then task2
BOutputs results of task1 and task2 as they complete, order not guaranteed
COnly task1 result is logged, task2 is ignored
DThrows an error because workers array is empty after first pop
Step-by-Step Solution
Solution:
  1. Step 1: Understand worker allocation and reuse

    The pool starts with 2 workers. Each runTask pops a worker, uses it, then pushes it back after message received.
  2. Step 2: Analyze concurrency and output order

    Both tasks run concurrently on separate workers. Results log as tasks complete, order may vary.
  3. Final Answer:

    Outputs results of task1 and task2 as they complete, order not guaranteed -> Option B
  4. Quick Check:

    Workers reused, tasks run concurrently [OK]
Quick Trick: Workers pop and push back, tasks run in parallel [OK]
Common Mistakes:
  • Assuming workers array empties causing error
  • Thinking tasks run one after another
  • Believing only first task logs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes