Sharing a Counter Deliberately

The workers now return your Ridge and Harbor summaries, each built from a clone of the samples you sent. The shift lead also wants the total number of samples processed: three from Ridge and two from Harbor, so 5. Adding up the counts the workers send back is still the dashboard’s default. Here you’ll try the alternative on purpose: two threads writing one shared number, which is where JavaScript stops protecting you.

In this lesson, you’ll share that counter, update it safely, and see when to move a buffer instead.

Give Workers One Counter to Share

In Python, a process can’t change a plain variable in another process, so a shared counter lives in shared memory. multiprocessing.Value gives you one, with a lock you take around every update:

Language: Python
from multiprocessing import Process, Value

def tally(samples, processed):
    with processed.get_lock():
        processed.value += len(samples)

if __name__ == "__main__":
    processed = Value("i", 0)
    stations = [[8, 12, 10], [4, 6]]
    workers = [
        Process(target=tally, args=(samples, processed))
        for samples in stations
    ]
    for worker in workers:
        worker.start()
    for worker in workers:
        worker.join()
    print(processed.value)

The parent prints 5 after joining both processes.

JavaScript builds shared numbers from two pieces. An ArrayBuffer, as created here, is a fixed-size block of raw bytes, like a bytearray you can’t index: you always read it through a view. An Int32Array is a view that reads the bytes as signed 32-bit integers, like memoryview(buf).cast("i"), so counts[0] is the first integer.

Like Value("i"), each slot wraps past 2,147,483,647 instead of growing like a Python int. A SharedArrayBuffer is a block of bytes that every thread holding it sees, instead of a copy.

The Ridge worker adds its sample count to the counter it got in workerData:

Language: JavaScript Filename: tally.mjs
import { workerData } from "node:worker_threads";

workerData.counts[0] += workerData.samples.length;

These workers post nothing back, so runTally() is your runWorker() helper minus the message. It resolves on a clean exit and rejects on an error event or a nonzero exit code. new URL(file, import.meta.url) finds the worker file next to this module, new Promise() makes the events awaitable, and you’ll use moved in the last section:

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

Become a Member to join the conversation.