Skip to content

Instantly share code, notes, and snippets.

@childrentime
Created October 30, 2023 09:45
Show Gist options
  • Save childrentime/d4d43672fad2a0bf3dda35fda290dbc1 to your computer and use it in GitHub Desktop.
Save childrentime/d4d43672fad2a0bf3dda35fda290dbc1 to your computer and use it in GitHub Desktop.
Nodejs Thread Concurrency
import { fileURLToPath } from "node:url";
import { Worker, isMainThread, workerData } from "worker_threads";
const __filename = fileURLToPath(import.meta.url);
if (isMainThread) {
const sharedBuffer = new SharedArrayBuffer(1 * Int32Array.BYTES_PER_ELEMENT);
const sharedArray = new Int32Array(sharedBuffer);
const worker1 = new Worker(__filename, { workerData: sharedBuffer });
const worker2 = new Worker(__filename, { workerData: sharedBuffer });
worker1.on("exit", () => {
console.log(sharedArray);
});
worker2.on("exit", () => {
console.log(sharedArray);
});
} else {
const sharedArray = new Int32Array(workerData);
for (let i = 0; i < 10000; i++) {
// thread race condition
sharedArray[0]++;
// solution
// Atomics.add(sharedArray, 0, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment