代码如下
index.js
const { Worker } = require('worker_threads');
const path = require('path');
const worker = new Worker(path.join(__dirname, './child.js'));
worker.on('message', (result) => {
console.log(result);
});
worker.on('error', (err) => {
console.log(err);
console.log('出错误了');
})
worker.postMessage({'a': 'a'});
child.js
const { parentPort } = require('worker_threads');
const a = (m, n) => {
return m + n;
}
parentPort.on('message', (msg) => {
console.log(msg);
const result = a(2, 3);
console.log('aaaaa');
parentPort.postMessage(result);
});
打印结果
为什么 aaaaa 在 5 之后打印, 谢谢