CodeBlanks Logo Icon CodeBlanks

Summary - Worker threads

Combine Worker, postMessage and SharedArrayBuffer to write a parallel computation.

Summary - Worker threads

In this group you learned the worker_threads module: you start threads with new Worker and exchange messages with postMessage. MessageChannel gives a two-port channel, and SharedArrayBuffer provides shared memory.

cluster creates separate processes; worker_threads creates parallel threads inside one process. For CPU-heavy work worker_threads is better; for network load cluster is more suitable. You can even combine them.

When to use worker_threads

worker_threads is for CPU-heavy work: image processing, big math, cryptography, file compression. If these block the event loop, requests stall.

For I/O-heavy work (network, disk) worker_threads is unnecessary; Node.js's event loop and async I/O already handle it. Measure first, then add threads. Unneeded threads add complexity.

Practice Log main or worker

If isMainThread is true log "main", otherwise log "worker".

Starter code

index.js
// import the module, get the main flag

// log "main" or "worker" based on the flag

Sample solution

index.js
const { isMainThread } = require("worker_threads");
console.log(isMainThread ? "main" : "worker");

Expected output

main

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main difference between cluster and worker_threads?

  • They are the same thing
  • cluster uses separate processes, worker_threads uses parallel threads Correct answer
  • cluster is networking, worker_threads is a database
  • cluster reads files, worker_threads writes them

Explanation: cluster uses separate processes; worker_threads uses parallel threads in one process.

2 Match each piece to its role

Term Meaning
new Worker Starts a thread
postMessage Sends message
MessageChannel Two-port channel
SharedArrayBuffer Shared memory

All lessons in Advanced