0

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!

Howard F
  • 138
  • 12
  • 1
    If you don't use [atomics](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics), you're not guaranteed the correct result. – Patrick Roberts Jul 04 '22 at 16:32
  • @PatrickRoberts I see, is there possible any work around using DataView else is cool tho. – Howard F Jul 04 '22 at 17:31
  • You could implement a class that has the same interface as DataView but its implementation uses atomics. I tried to find an npm module that does that but it doesn't appear there is one. – Patrick Roberts Jul 04 '22 at 17:40

0 Answers0