worker.postMessageToThread(threadId, value[, transferList][, timeout])


稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

将值发送给另一个由其线程 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 { once } from 'node:events';
import process from 'node:process';
import {
  isMainThread,
  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 { once } = require('node:events');
const {
  isMainThread,
  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;