From 2e8dfee16560ce445fad3de3574987532814bd04 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 12 May 2021 13:36:56 -0700 Subject: [PATCH] doc: clarify synchronous blocking of Worker stdio Fixes: https://github.com/nodejs/node/issues/25630 Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/38658 Reviewed-By: Anna Henningsen Reviewed-By: Antoine du Hamel --- doc/api/worker_threads.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 7b414a5d1a2263..b39ef6749dd952 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -968,6 +968,45 @@ active handle in the event system. If the worker is already `unref()`ed calling ## Notes +### Synchronous blocking of stdio + +`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. + +```mjs +import { + Worker, + isMainThread, +} from 'worker_threads'; + +if (isMainThread) { + new Worker(new URL(import.meta.url)); + for (let n = 0; n < 1e10; n++) {} +} else { + // This output will be blocked by the for loop in the main thread. + console.log('foo'); +} +``` + +```cjs +'use strict'; + +const { + Worker, + isMainThread, +} = require('worker_threads'); + +if (isMainThread) { + new Worker(__filename); + for (let n = 0; n < 1e10; n++) {} +} else { + // This output will be blocked by the for loop in the main thread. + console.log('foo'); +} +``` + ### Launching worker threads from preload scripts Take care when launching worker threads from preload scripts (scripts loaded