Created
October 30, 2023 09:45
-
-
Save childrentime/d4d43672fad2a0bf3dda35fda290dbc1 to your computer and use it in GitHub Desktop.
Nodejs Thread Concurrency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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