Worker threads run in the same process and share memory, allowing faster communication. Child processes run independently with separate memory, requiring message passing.
const { Worker } = require('worker_threads');
const { fork } = require('child_process');
console.log('Main start');
const worker = new Worker(`
const { parentPort } = require('worker_threads');
parentPort.postMessage('Worker done');
`, { eval: true });
const child = fork('./child.js');
worker.on('message', msg => console.log(msg));
child.on('message', msg => console.log(msg));
console.log('Main end');The main thread logs 'Main start' and 'Main end' immediately. Worker thread and child process send messages asynchronously, so their messages appear after main logs.
const { fork } = require('child_process');
const child = fork('child.js');
child.send('Hello parent');
// child.js content:
// process.on('message', msg => {
// console.log('Message from parent:', msg);
// });The parent process uses child.send() to send a message to the child process. This works if the child process listens for 'message' events. No error occurs here.
Option B correctly uses a template string with inline code and sets eval: true. Option B misses eval: true, so it will error. Options B and C do not use parentPort, so they won't communicate properly.
let count = 0; // Worker thread increments count by 1 // Child process increments count by 1 // After both finish, what is count in main thread?
Neither worker threads nor child processes can directly change variables in the main thread. Worker threads share memory but require explicit shared memory objects. Child processes have separate memory. So main thread's 'count' remains unchanged.