stdio 的同步阻塞
\Synchronous blocking of stdio
Worker 利用通过 <MessagePort> 传递的消息来实现与 stdio 的交互。这意味着来自 Worker 的 stdio 输出可能会被接收端的同步代码阻塞,这会阻塞 Node.js 事件循环。
\Workers 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 'node: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'); }