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:
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:
{'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:
station.mjs
export const samples = [8, 12, 10];
export const totals = {};