0Pricing
Node.js Backend Development Bootcamp · บทเรียน

การสร้างเธรดผู้ปฏิบัติงานและการส่งข้อความ

สร้างผู้ปฏิบัติงาน แลกเปลี่ยนข้อมูลผ่าน postMessage และใช้ workerData กับ MessageChannel เพื่อการสื่อสารแบบมีโครงสร้าง

การสร้างเธรดผู้ปฏิบัติงานและการส่งข้อความ เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Worker Threads Exist

Node.js runs your JavaScript on a single thread. That is great for I/O-bound work (HTTP, DB, files) because the event loop never blocks. But a CPU-bound task — image resizing, hashing, parsing huge payloads, crypto — runs synchronously and freezes the entire server until it finishes.

  • I/O-bound → stay on the event loop, use async APIs.
  • CPU-bound → offload to a Worker thread so the main thread keeps serving requests.

The worker_threads module lets you run JavaScript in parallel on separate OS threads, each with its own V8 isolate and event loop.

Spawning Your First Worker

You create a thread with new Worker(filename). The file runs on a fresh thread. Use isMainThread to make one file behave differently depending on where it runs.

Below, the main thread spawns a worker that points back to the same file. The worker branch does the work and exits.

const { Worker, isMainThread } = require('node:worker_threads');

if (isMainThread) {
  console.log('main: spawning worker');
  const worker = new Worker(__filename);
  worker.on('exit', (code) => console.log('worker exited with', code));
} else {
  // This branch runs inside the worker thread
  let sum = 0;
  for (let i = 0; i < 1e7; i++) sum += i;
  console.log('worker computed sum =', sum);
}

Sending Data In with workerData

To hand input to a worker at creation time, pass workerData in the options object. Inside the worker, read it from the worker_threads module.

  • workerData is cloned (structured clone), not shared — mutating it in the worker does not affect the main thread.
  • Use it for the initial job parameters: a file path, a number range, config.
const { Worker, isMainThread, workerData } = require('node:worker_threads');

if (isMainThread) {
  new Worker(__filename, { workerData: { start: 1, end: 5 } });
} else {
  const { start, end } = workerData;
  let product = 1;
  for (let i = start; i <= end; i++) product *= i;
  console.log('factorial-ish product =', product);
}

Getting Results Back with postMessage

workerData is one-way and one-time. For results, use the message channel that every worker has built in:

  • Inside the worker: parentPort.postMessage(value) sends data to the parent.
  • On the main thread: worker.on('message', cb) receives it.

Messages are asynchronous and structured-cloned, so the main thread stays responsive while the worker computes.

const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename, { workerData: 40 });
  worker.on('message', (result) => {
    console.log('main received:', result);
  });
} else {
  function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
  parentPort.postMessage(fib(workerData));
}

Two-Way Messaging

The channel works both directions. The parent can worker.postMessage() and the worker listens with parentPort.on('message', ...). This turns a worker into a long-lived service that processes many jobs instead of one.

Notice the worker stays alive listening for messages; you must explicitly tell it to stop (here, a null sentinel triggers process.exit).

const { Worker, isMainThread, parentPort } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.on('message', (r) => console.log('squared ->', r));
  [2, 3, 4].forEach((n) => worker.postMessage(n));
  worker.postMessage(null); // sentinel to stop
} else {
  parentPort.on('message', (n) => {
    if (n === null) { process.exit(0); }
    parentPort.postMessage(n * n);
  });
}

Promisifying a Single Job

In backend code you usually want a clean async function: call it, await a result. Wrap the worker lifecycle in a Promise, resolving on message and rejecting on error or a non-zero exit.

This pattern is the foundation of any worker-pool: one promise per task.

const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');

function runJob(payload) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(__filename, { workerData: payload });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0) reject(new Error('exit code ' + code));
    });
  });
}

if (isMainThread) {
  runJob([5, 10, 15]).then((sum) => console.log('total =', sum));
} else {
  const total = workerData.reduce((a, b) => a + b, 0);
  parentPort.postMessage(total);
}

Structured Clone: What You Can Send

Messages are copied using the structured clone algorithm, not JSON.stringify. That means you can send more than plain JSON.

  • Supported: objects, arrays, Map, Set, Date, RegExp, ArrayBuffer, typed arrays, BigInt.
  • Not supported: functions, class instances with methods, DOM-like objects, anything with closures — these throw a DataCloneError.

Cloning large objects costs CPU and memory. For big binary buffers, prefer transferring instead of copying (next scene).

Transferring Buffers Instead of Copying

For large binary data, copying is wasteful. Pass a transfer list as the second argument to postMessage. Ownership of the ArrayBuffer moves to the other thread — zero-copy — and the buffer becomes unusable on the sender (its byteLength becomes 0).

Use this for image bytes, file chunks, or any megabyte-scale payload to avoid duplicating memory.

const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');

if (isMainThread) {
  const buf = new Uint8Array([1, 2, 3, 4]).buffer;
  const worker = new Worker(__filename, { workerData: buf }, { transferList: [buf] });
  worker.on('message', (sum) => console.log('byte sum =', sum));
} else {
  const bytes = new Uint8Array(workerData);
  let sum = 0;
  for (const b of bytes) sum += b;
  parentPort.postMessage(sum);
}

MessageChannel for Side Channels

Beyond the built-in parentPort, you can create your own channel with new MessageChannel(). It gives two linked ports, port1 and port2. Keep one, transfer the other into a worker, and now you have a dedicated pipe — useful for separating control messages from data, or for worker-to-worker communication.

A MessagePort is itself transferable, so you send it inside workerData or a message with a transfer list.

const { Worker, isMainThread, MessageChannel, parentPort, workerData } =
  require('node:worker_threads');

if (isMainThread) {
  const { port1, port2 } = new MessageChannel();
  new Worker(__filename, { workerData: { port: port2 }, transferList: [port2] });
  port1.on('message', (msg) => {
    console.log('main got on side channel:', msg);
    port1.close();
  });
  port1.postMessage('ping');
} else {
  const { port } = workerData;
  port.on('message', (msg) => {
    port.postMessage('pong (you said: ' + msg + ')');
  });
}

Handling Errors and Clean Shutdown

A worker can crash. Always wire up its lifecycle events so a failed job does not silently hang a request:

  • 'error' — an uncaught exception inside the worker.
  • 'exit' — fired once; code is non-zero on failure.
  • 'messageerror' — a message could not be deserialized.

To stop a worker from the main thread, call worker.terminate() (returns a promise). Unterminated workers keep the process alive.

const { Worker, isMainThread, parentPort } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.on('error', (err) => console.log('caught worker error:', err.message));
  worker.on('exit', (code) => console.log('exited, code =', code));
} else {
  throw new Error('boom inside worker');
}

A Practical Backend Shape

In a real Node.js backend you do not spawn a worker per request — thread startup is expensive. Instead:

  • Keep a small pool of long-lived workers (often os.cpus().length).
  • Send each CPU-bound job over postMessage and match results by an id.
  • Reserve workers for genuinely CPU-bound work; leave I/O on the event loop.

This snippet shows the per-worker message protocol using an id to correlate request and response — the core idea every pool library (like piscina) builds on.

const { Worker, isMainThread, parentPort } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  const pending = new Map();
  let nextId = 0;
  worker.on('message', ({ id, result }) => {
    pending.get(id)(result);
    pending.delete(id);
    if (pending.size === 0) worker.terminate();
  });
  function submit(payload) {
    return new Promise((res) => {
      const id = nextId++;
      pending.set(id, res);
      worker.postMessage({ id, payload });
    });
  }
  Promise.all([submit(3), submit(7)]).then((r) => console.log('results:', r));
} else {
  parentPort.on('message', ({ id, payload }) => {
    parentPort.postMessage({ id, result: payload * payload });
  });
}

Quick Check

You must send a 50 MB image buffer to a worker for processing and you want to avoid duplicating that memory. Which approach is correct?

Recap

You now know how to spawn workers and move data between threads:

  • Spawn with new Worker(file, { workerData }); branch on isMainThread.
  • Send results with parentPort.postMessage() and receive via worker.on('message') — the channel is two-way.
  • Messages use structured clone (richer than JSON, but no functions); large buffers should be transferred via a transfer list for zero-copy.
  • Create extra pipes with MessageChannel and transfer a MessagePort for side or worker-to-worker channels.
  • Always handle error/exit and call terminate(); in production use a pool with id-correlated messages rather than one worker per request.

คำถามที่พบบ่อย

บทเรียน “การสร้างเธรดผู้ปฏิบัติงานและการส่งข้อความ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างเธรดผู้ปฏิบัติงานและการส่งข้อความ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างเธรดผู้ปฏิบัติงานและการส่งข้อความ”

สร้างผู้ปฏิบัติงาน แลกเปลี่ยนข้อมูลผ่าน postMessage และใช้ workerData กับ MessageChannel เพื่อการสื่อสารแบบมีโครงสร้าง คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างเธรดผู้ปฏิบัติงานและการส่งข้อความ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เหตุใดลูปเหตุการณ์จึงหยุดชะงักเมื่อทำงานที่ใช้ CPU สูง
  2. การสร้างเธรดผู้ปฏิบัติงานและการส่งข้อความ
  3. การแชร์หน่วยความจำด้วย SharedArrayBuffer และอะตอมิกส์
  4. การสร้างกลุ่มผู้ปฏิบัติงานแบบใช้ซ้ำได้เพื่อเพิ่มปริมาณงาน
← กลับไปที่ Node.js Backend Development Bootcamp