worker.postMessageToThread(threadId, value[, transferList][, timeout])
¥Stability: 1.1 - Active development
-
threadId<number> 目标线程 ID。如果线程 ID 无效,则将抛出ERR_WORKER_MESSAGING_FAILED错误。如果目标线程 ID 是当前线程 ID,则将抛出ERR_WORKER_MESSAGING_SAME_THREAD错误。¥
threadId<number> The target thread ID. If the thread ID is invalid, aERR_WORKER_MESSAGING_FAILEDerror will be thrown. If the target thread ID is the current thread ID, aERR_WORKER_MESSAGING_SAME_THREADerror will be thrown. -
value<any> 要发送的值。¥
value<any> The value to send. -
transferList<Object[]> 如果在value中传入一个或多个类似MessagePort的对象,则这些条目需要transferList或抛出ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST。有关详细信息,请参阅port.postMessage()。¥
transferList<Object[]> If one or moreMessagePort-like objects are passed invalue, atransferListis required for those items orERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LISTis thrown. Seeport.postMessage()for more information. -
timeout<number> 等待消息传递的时间(以毫秒为单位)。默认情况下是undefined,这意味着永远等待。如果操作超时,则抛出ERR_WORKER_MESSAGING_TIMEOUT错误。¥
timeout<number> Time to wait for the message to be delivered in milliseconds. By default it'sundefined, which means wait forever. If the operation times out, aERR_WORKER_MESSAGING_TIMEOUTerror is thrown. -
返回:<Promise> 如果目标线程成功处理了消息,则实现 promise。
¥Returns: <Promise> A promise which is fulfilled if the message was successfully processed by destination thread.
将值发送给另一个由其线程 ID 标识的工作程序。
¥Sends a value to another worker, identified by its thread ID.
如果目标线程没有 workerMessage 事件的监听器,则操作将抛出 ERR_WORKER_MESSAGING_FAILED 错误。
¥If the target thread has no listener for the workerMessage event, then the operation will throw
a ERR_WORKER_MESSAGING_FAILED error.
如果目标线程在处理 workerMessage 事件时抛出错误,则操作将抛出 ERR_WORKER_MESSAGING_ERRORED 错误。
¥If the target thread threw an error while processing the workerMessage event, then the operation will throw
a ERR_WORKER_MESSAGING_ERRORED error.
当目标线程不是当前线程的直接父线程或子线程时,应使用此方法。如果两个线程是父子线程,则使用 require('node:worker_threads').parentPort.postMessage() 和 worker.postMessage() 让线程进行通信。
¥This method should be used when the target thread is not the direct
parent or child of the current thread.
If the two threads are parent-children, use the require('node:worker_threads').parentPort.postMessage()
and the worker.postMessage() to let the threads communicate.
以下示例显示了 postMessageToThread 的用法:它创建了 10 个嵌套线程,最后一个将尝试与主线程通信。
¥The example below shows the use of of postMessageToThread: it creates 10 nested threads,
the last one will try to communicate with the main thread.
import { fileURLToPath } from 'node:url';
import process from 'node:process';
import {
postMessageToThread,
threadId,
workerData,
Worker,
} from 'node:worker_threads';
const channel = new BroadcastChannel('sync');
const level = workerData?.level ?? 0;
if (level < 10) {
const worker = new Worker(fileURLToPath(import.meta.url), {
workerData: { level: level + 1 },
});
}
if (level === 0) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
postMessageToThread(source, { message: 'pong' });
});
} else if (level === 10) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
channel.postMessage('done');
channel.close();
});
await postMessageToThread(0, { message: 'ping' });
}
channel.onmessage = channel.close;const {
postMessageToThread,
threadId,
workerData,
Worker,
} = require('node:worker_threads');
const channel = new BroadcastChannel('sync');
const level = workerData?.level ?? 0;
if (level < 10) {
const worker = new Worker(__filename, {
workerData: { level: level + 1 },
});
}
if (level === 0) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
postMessageToThread(source, { message: 'pong' });
});
} else if (level === 10) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
channel.postMessage('done');
channel.close();
});
postMessageToThread(0, { message: 'ping' });
}
channel.onmessage = channel.close;