Bird
Raised Fist0
Node.jsframework~10 mins

Worker thread vs child process in Node.js - Visual Side-by-Side Comparison

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Worker thread vs child process
Main Process
Create Worker Thread
Create Child Process
Communication via Messages
Worker Thread shares memory
Faster communication
The main process can create either a worker thread or a child process. Worker threads run in the same memory space, while child processes run separately. Both communicate via messages.
Execution Sample
Node.js
import { Worker } from 'worker_threads';
import { fork } from 'child_process';

const worker = new Worker('./worker.js');
const child = fork('./child.js');
This code creates a worker thread and a child process from the main Node.js process.
Execution Table
StepActionProcess/ThreadMemory SpaceCommunicationResult
1Main process startsMainMain memoryN/AMain process running
2Create Worker ThreadWorker ThreadShared with mainMessage passing + SharedArrayBufferWorker thread running in same process
3Create Child ProcessChild ProcessSeparate from mainMessage passing (IPC)Child process running independently
4Worker sends messageWorker ThreadShared memoryFast message passingMain receives message quickly
5Child sends messageChild ProcessSeparate memoryIPC message passingMain receives message with overhead
6Worker accesses shared memoryWorker ThreadShared memoryDirect memory accessData shared efficiently
7Child accesses memoryChild ProcessOwn memoryNo shared memoryData must be serialized
8Main process endsMainMain memoryN/AWorker and child processes terminate or continue based on code
💡 Execution stops when main process ends or all workers/child processes exit.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
workerThreadundefinedWorker instance createdWorker runningMessage sentMessage acknowledgedWorker running or terminated
childProcessundefinedundefinedChild process forkedundefinedMessage sentChild running or terminated
sharedMemoryN/AAllocated and sharedN/AAccessed by workerN/AShared data updated or cleared
Key Moments - 3 Insights
Why does the worker thread have faster communication with the main process than the child process?
Because the worker thread shares the same memory space with the main process, allowing direct memory access and faster message passing, as shown in steps 4 and 6 of the execution_table.
Can the child process directly access the main process memory?
No, the child process runs in a separate memory space and must use message passing with serialization to communicate, as shown in steps 3 and 7.
What happens if the main process ends while worker threads or child processes are still running?
Typically, worker threads and child processes will terminate or continue based on how the code handles their lifecycle, as noted in step 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the worker thread send a message to the main process?
AStep 4
BStep 5
CStep 2
DStep 7
💡 Hint
Check the 'Action' and 'Process/Thread' columns in execution_table rows.
According to variable_tracker, what is the state of 'childProcess' after Step 3?
Aundefined
BChild process forked
CMessage sent
DChild process terminated
💡 Hint
Look at the 'childProcess' row and 'After Step 3' column in variable_tracker.
If the worker thread did not share memory, how would communication speed change compared to the child process?
AIt would be slower than child process communication
BIt would be the same as child process communication
CIt would be faster than child process communication
DIt would not be able to communicate
💡 Hint
Refer to the 'Memory Space' and 'Communication' columns in execution_table.
Concept Snapshot
Worker threads run in the same process and share memory, enabling fast communication.
Child processes run separately with isolated memory, communicating via message passing.
Use worker threads for lightweight parallel tasks needing shared memory.
Use child processes for heavy or isolated tasks needing separate memory.
Both communicate asynchronously via messages.
Choose based on task isolation and communication needs.
Full Transcript
This visual execution compares worker threads and child processes in Node.js. The main process can create a worker thread, which runs JavaScript in the same memory space, or a child process, which runs independently with separate memory. Worker threads communicate faster because they share memory, allowing direct access and fast message passing. Child processes communicate via inter-process communication, which involves serialization and is slower. Variables like workerThread and childProcess track their creation and message passing states. Key moments include understanding memory sharing and communication speed differences. Quizzes test knowledge on message steps, variable states, and communication speed implications. The snapshot summarizes when to use each approach based on memory sharing and task isolation.

Practice

(1/5)
1. Which statement best describes the difference between worker threads and child processes in Node.js?
easy
A. Worker threads run in the same process sharing memory, while child processes run in separate processes with separate memory.
B. Worker threads run separate programs, child processes share the same memory space.
C. Both worker threads and child processes run in the same process and share memory.
D. Child processes run inside worker threads to improve performance.

Solution

  1. Step 1: Understand worker threads behavior

    Worker threads run JavaScript code in parallel but inside the same Node.js process and share memory.
  2. Step 2: Understand child processes behavior

    Child processes run completely separate programs with their own memory space and communicate via messages.
  3. Final Answer:

    Worker threads run in the same process sharing memory, while child processes run in separate processes with separate memory. -> Option A
  4. Quick Check:

    Worker threads share memory, child processes do not [OK]
Hint: Remember: threads share memory, processes do not [OK]
Common Mistakes:
  • Confusing memory sharing between threads and processes
  • Thinking child processes share memory
  • Assuming worker threads run separate programs
2. Which of the following is the correct way to create a worker thread in Node.js?
easy
A. const worker = spawn('worker.js');
B. const worker = fork('worker.js');
C. const worker = createThread('worker.js');
D. const worker = new Worker('worker.js');

Solution

  1. Step 1: Recall worker thread creation syntax

    Worker threads are created using the Worker class from the worker_threads module.
  2. Step 2: Identify correct constructor usage

    The correct syntax is new Worker('filename'). The fork and spawn methods are for child processes.
  3. Final Answer:

    const worker = new Worker('worker.js'); -> Option D
  4. Quick Check:

    Worker threads use new Worker() [OK]
Hint: Use new Worker() for threads, fork/spawn for processes [OK]
Common Mistakes:
  • Using fork() to create worker threads
  • Using spawn() for worker threads
  • Using non-existent createThread() function
3. Consider this Node.js code snippet using a child process:
const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', msg => console.log('Parent got:', msg));
child.send('Hello');

What will the parent process output if child.js sends back { reply: 'Hi' } on receiving a message?
medium
A. Parent got: Hello
B. Parent got: { reply: 'Hi' }
C. Parent got: Hi
D. No output, error occurs

Solution

  1. Step 1: Understand child process communication

    The parent sends 'Hello' to the child. The child responds with an object { reply: 'Hi' } via process.send().
  2. Step 2: Analyze parent's message event handler

    The parent's child.on('message') receives the object and logs it as Parent got: { reply: 'Hi' }.
  3. Final Answer:

    Parent got: { reply: 'Hi' } -> Option B
  4. Quick Check:

    Child sends object, parent logs object [OK]
Hint: Child sends object, parent logs exact message [OK]
Common Mistakes:
  • Assuming string 'Hi' instead of object
  • Expecting parent's message to be 'Hello'
  • Confusing child and parent message directions
4. What is wrong with this code snippet that tries to create a worker thread?
const { Worker } = require('worker_threads');
const worker = Worker('worker.js');
medium
A. The file 'worker.js' must be a JSON file
B. Wrong module imported, should be 'child_process'
C. Missing new keyword before Worker constructor
D. Worker threads cannot be created with a filename

Solution

  1. Step 1: Check Worker thread creation syntax

    The Worker class must be instantiated with the new keyword.
  2. Step 2: Identify error in code

    The code calls Worker('worker.js') without new, causing a TypeError.
  3. Final Answer:

    Missing new keyword before Worker constructor -> Option C
  4. Quick Check:

    Use new Worker() to create threads [OK]
Hint: Always use new with Worker() constructor [OK]
Common Mistakes:
  • Forgetting new keyword
  • Importing wrong module for threads
  • Thinking worker.js must be JSON
5. You want to perform a CPU-heavy task in Node.js without blocking the main event loop. Which approach is best and why?
hard
A. Use a child process to run the task in a separate process communicating via messages.
B. Use a worker thread to run the task sharing memory with the main thread.
C. Run the task directly in the main thread asynchronously.
D. Use setTimeout to delay the task execution in the main thread.

Solution

  1. Step 1: Understand CPU-heavy task impact

    CPU-heavy tasks block the main event loop if run directly, causing app unresponsiveness.
  2. Step 2: Compare worker threads and child processes for heavy tasks

    Worker threads share memory but still run in the same process, which can cause contention. Child processes run in separate processes, isolating CPU load and preventing blocking.
  3. Step 3: Evaluate other options

    Running asynchronously in main thread or delaying with setTimeout does not prevent blocking for CPU-heavy tasks.
  4. Final Answer:

    Use a child process to run the task in a separate process communicating via messages. -> Option A
  5. Quick Check:

    Heavy CPU tasks best isolated in child processes [OK]
Hint: Heavy CPU tasks? Use child processes to avoid blocking [OK]
Common Mistakes:
  • Assuming worker threads fully isolate CPU load
  • Thinking async or setTimeout avoids CPU blocking
  • Ignoring message communication overhead