I was just tinkering and messing around with worker thread in NodeJS and managed to do so in a fundamental way. But running the child process and expecting result to be "30,000" after running 3 workers but occasionally get incorrect value.
// main.js
const { exit } = require('process');
const { Worker } = require('worker_threads');
const SharedResult = require('./result');
const SHARED_ARRAY_BUFFER = new SharedArrayBuffer(4);
const Result = new SharedResult(SHARED_ARRAY_BUFFER);
function runWorker() {
return new Promise(function(resolve) {
const w = new Worker('./child.js');
w.on('message', (result) => {
resolve();
});
w.postMessage({ SHARED_ARRAY_BUFFER });
});
}
console.log('Before', Result.x);
console.time();
Promise.all([runWorker(), runWorker(), runWorker()])
.then((res) => {
console.log('After', Result.x); // Expected always get "30000" but some is lesser than that.
console.timeEnd();
exit();
});
// child.js
const { parentPort } = require('worker_threads');
const SharedResult = require('./result');
parentPort.on('message', (data) => {
const { SHARED_ARRAY_BUFFER } = data;
const Result = new SharedResult(SHARED_ARRAY_BUFFER);
for (let i = 0; i < 10000; i++) {
Result.x++;
}
parentPort.postMessage({ });
});
// result.js, just to use DataView like an object
class SharedPoint {
constructor(array) {
this.dataview = new DataView(array);
}
set x(value) {
this.dataview.setUint32(0, value);
}
get x() {
return this.dataview.getUint32(0);
}
}
module.exports = SharedPoint;
I only can know this is wrong approach to run logic like this using worker thread from my opinion. Thanks!