node v10.16.3
I was running an worker_threads
example from node official doc. I made some changes as want to test share variables. Here is an example
work-thread.js
const {
Worker,
isMainThread,
parentPort,
workerData
} = require("worker_threads");
let a = 10;
if (isMainThread) {
module.exports = async function parseJSAsync(num) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: num
});
worker.on("message", resolve);
worker.on("error", reject);
worker.on("exit", code => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
for (let i = 0; i < num; i++) {
console.log("master: ", a);
a++;
}
});
};
} else {
const num = workerData;
let result = 1;
for (let i = 1; i < num; i++) {
console.log("worker: ", a);
a--;
result = result * i;
}
parentPort.postMessage(result);
}
And there is a script for testing this example:
const calculateFactorial = require("./work-thread");
calculateFactorial(10).then(res => console.log("res", res));
There is an a
can be accessed by both main thread and worker thread.
When I run this code, the output is
master: 10
master: 11
master: 12
master: 13
master: 14
master: 15
master: 16
master: 17
master: 18
master: 19
worker: 10
res 362880
worker: 9
worker: 8
worker: 7
worker: 6
worker: 5
worker: 4
worker: 3
worker: 2
I wonder why worker's postMessage is earlier than worker's console.log