Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Moving CPU Work to a Worker

Moving CPU Work to a Worker

In this lesson, you put a station summary in a worker. Summing a long batch of samples is CPU work, and while it runs, timers and polls wait, as you saw when a timer waited for your code. Ridge’s three samples stand in for that batch.

JavaScript’s tool for this is called a worker thread, so a line-by-line port starts from a Python thread. The script keeps samples and a totals dictionary at module level, and summarize() stores Ridge’s sum in totals. A threading.Thread runs it: start() begins the thread, and join() waits for it to finish:

Language: Python
import threading

samples = [8, 12, 10]
totals = {}

def summarize():
    totals["Ridge"] = sum(samples)

worker = threading.Thread(target=summarize)
worker.start()
worker.join()
print(totals)

The script prints Ridge with a total of thirty:

Language: Program Output
{'Ridge': 30}

In JavaScript, a worker comes from Node’s node:worker_threads module, and its code lives in a file of its own. So the module-level data moves to station.mjs, which both files import:

Language: JavaScript Filename: station.mjs
export const samples = [8, 12, 10];
export const totals = {};

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 In this lesson, you’ll put a station summary in a worker. Summing a long batch of samples is CPU work, and while it runs, timers and polls wait, as you saw when a timer waited for your code.

00:12 Ridge’s three samples stand in for that batch. JavaScript’s tool for this is called a worker thread, so a line-by-line port starts from a Python thread. The script keeps samples and a totals dictionary at module level, and summarize() stores Ridge’s sum in totals.

00:31 A threading.Thread runs it: start() begins the thread, join() waits for it to finish, and the script prints Ridge with a total of thirty.

00:41 In JavaScript, a worker comes from Node’s node:worker_threads module, and its code lives in a file of its own. So the module-level data moves to station.mjs, which both files import.

00:55 worker.mjs sums the samples with .reduce(), which combines an array into one value from a start of zero, like sum() in Python.

01:04 Then it stores the total in totals.

01:08 main.mjs imports Worker and the same totals. import.meta.url is the module’s own file as a URL, like Python’s __file__, and new URL() resolves ./worker.mjs against it, so the path works from any folder.

01:26 new Worker() starts the worker at once: there’s no start() to call. worker.once() runs a listener the first time an event fires.

01:34 The exit event fires when the worker has finished, like join() returning, but without blocking: then the listener logs totals.

01:41 What does main.mjs log? Your turn: pause the video and predict.

01:52 An empty object.

01:56 The worker did store the total. Log totals on both sides: the worker shows Ridge at thirty, the main thread an empty object.

02:06 A worker is a separate JavaScript instance with its own memory. It loads its own copy of every module it imports, so station.mjs runs twice, and there are two totals objects.

02:20 Python’s threads share one set of modules, so the thread’s write showed up. A worker is closer to a multiprocessing process: with a Process in place of the thread, Python prints an empty dictionary too.

02:33 Unlike a process, though, a worker is a thread inside the same Node process.

02:40 Nothing crosses over unless you send it; shared memory comes later in the course. In worker.mjs, workerData holds what the main thread sent, and parentPort.postMessage() sends { total } back, shorthand for { total: total }.

02:58 Watch out: workerData and every message arrive as a structured clone, a copy made when they’re sent, so a change on one side never reaches the other.

03:08 In main.mjs, the workerData option hands the worker Ridge’s samples, and a message listener receives the copy. The main thread logs a total of thirty.

03:19 A multiprocessing pool pickles copies of its arguments and results too.

03:25 A message alone doesn’t say when the worker is done, or whether it failed. So runWorker() wraps the worker in new Promise(). The function you pass gets resolve and reject, and calling one settles the promise, like setting a result or an exception on an asyncio future.

03:43 The message listener keeps the result; the error listener keeps a thrown error. Both have no value at first, which counts as false, like None.

03:52 The exit listener settles the promise. It resolves only when the exit code is zero and a result arrived; && is Python’s and.

04:02 Otherwise, it rejects, and the template literal, a backtick string, fills in the code like an f-string. await runWorker() returns after the worker has exited, and the main thread logs a total of thirty.

04:17 A worker that throws exits with code one, and the promise rejects with a copy of its error. One that ends itself with code two rejects with Worker exit 2 as its message.

04:28 Either way, the worker has exited before the await returns.

04:33 So put CPU work in a worker file, send its input as workerData and its result with postMessage(), and settle a promise on the worker’s exit event.

04:42 Don’t expect module state to cross over: each worker has its own.

04:48 Next up is the exercise Summarize a Second Station in a Worker. There, you’ll summarize another station’s samples in a worker.

Become a Member to join the conversation.