标准输入输出的同步阻塞
Worker
利用通过 <MessagePort> 传入的消息来实现与 stdio
的交互。
这意味着来自 Worker
的 stdio
输出可能会被接收端的同步代码阻塞,这会阻塞 Node.js 事件循环。
import {
Worker,
isMainThread,
} from 'worker_threads';
if (isMainThread) {
new Worker(new URL(import.meta.url));
for (let n = 0; n < 1e10; n++) {
// 循环模拟工作。
}
} else {
// 此输出将被主线程中的 for 循环阻塞。
console.log('foo');
}
'use strict';
const {
Worker,
isMainThread,
} = require('node:worker_threads');
if (isMainThread) {
new Worker(__filename);
for (let n = 0; n < 1e10; n++) {
// 循环模拟工作。
}
} else {
// 此输出将被主线程中的 for 循环阻塞。
console.log('foo');
}
Worker
s utilize message passing via <MessagePort> to implement interactions
with stdio
. This means that stdio
output originating from a Worker
can
get blocked by synchronous code on the receiving end that is blocking the
Node.js event loop.
import {
Worker,
isMainThread,
} from 'worker_threads';
if (isMainThread) {
new Worker(new URL(import.meta.url));
for (let n = 0; n < 1e10; n++) {
// Looping to simulate work.
}
} else {
// This output will be blocked by the for loop in the main thread.
console.log('foo');
}
'use strict';
const {
Worker,
isMainThread,
} = require('node:worker_threads');
if (isMainThread) {
new Worker(__filename);
for (let n = 0; n < 1e10; n++) {
// Looping to simulate work.
}
} else {
// This output will be blocked by the for loop in the main thread.
console.log('foo');
}