问题
Here's an example with worker thread that takes ~600ms on local machine for synchronous I/O:
const fs = require('fs');
const { isMainThread, Worker, parentPort, workerData } = require('worker_threads');
const filename = './foo.txt';
if (isMainThread) {
(async () => {
console.time('!');
await new Promise((resolve, reject) => {
const worker = new Worker(__filename, { workerData: filename });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
console.timeEnd('!');
})().catch(console.error);
} else {
for (let i = 0; i < 100; i++)
fs.readFileSync(workerData);
parentPort.postMessage('ok');
}
The same example with single thread takes ~2s for asynchronous I/O:
const fs = require('fs');
const filename = './foo.txt';
console.time('worker');
(function read(i) {
if (i < 100) {
fs.readFile(filename, () => read(++i));
return;
}
console.timeEnd('worker');
})(0);
Obviously, synchronous blocking operation is more efficient here.
Node.js worker thread reference states:
Workers are useful for performing CPU-intensive JavaScript operations; do not use them for I/O, since Node.js’s built-in mechanisms for performing operations asynchronously already treat it more efficiently than Worker threads can.
What are the grounds for this statement?
What is the difference between main and worker threads regarding I/O?
Isn't the purpose of a worker to not be limited to non-blocking asynchronous operations?
What are the circumstances under which I/O performance may be less efficient in worker threads?
来源:https://stackoverflow.com/questions/52648229/i-o-performance-in-node-js-worker-threads