Bird
0
0

Given this code snippet, what will be logged when run on a machine with 4 CPU cores?

medium📝 component behavior Q13 of 15
Node.js - Cluster Module
Given this code snippet, what will be logged when run on a machine with 4 CPU cores?
const cluster = require('cluster');
const os = require('os');

if (cluster.isPrimary) {
  const numCPUs = os.cpus().length;
  console.log(`Primary process is running`);
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  console.log(`Worker ${process.pid} started`);
}
APrimary process is running Worker 1234 started Worker 1235 started Worker 1236 started Worker 1237 started
BPrimary process is running Worker started Worker started Worker started Worker started
CPrimary process is running Worker 1234 started
DSyntaxError due to missing cluster setup
Step-by-Step Solution
Solution:
  1. Step 1: Identify primary and worker behavior

    The primary logs once and forks 4 workers (one per CPU core).
  2. Step 2: Each worker logs its own process id

    Each worker logs "Worker [pid] started" with its unique process id.
  3. Final Answer:

    Primary process is running Worker 1234 started Worker 1235 started Worker 1236 started Worker 1237 started -> Option A
  4. Quick Check:

    Primary logs once, 4 workers log with pids [OK]
Quick Trick: Primary logs once; each worker logs with unique pid [OK]
Common Mistakes:
  • Assuming workers log without pid
  • Thinking only one worker starts
  • Confusing primary and worker logs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes