worker.parentPort


如果此线程是作为 Worker 衍生的,这将是允许与父线程通信的 MessagePort。 使用 parentPort.postMessage() 发送的消息将在使用 worker.on('message') 的父线程中可用,使用 worker.postMessage() 从父线程发送的消息将在使用 parentPort.on('message') 的该线程中可用。

const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.once('message', (message) => {
    console.log(message);  // 打印 'Hello, world!'。
  });
  worker.postMessage('Hello, world!');
} else {
  // 当收到来自父线程的消息时,则将其发回:
  parentPort.once('message', (message) => {
    parentPort.postMessage(message);
  });
}

If this thread was spawned as a Worker, this will be a MessagePort allowing communication with the parent thread. Messages sent using parentPort.postMessage() will be available in the parent thread using worker.on('message'), and messages sent from the parent thread using worker.postMessage() will be available in this thread using parentPort.on('message').

const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.once('message', (message) => {
    console.log(message);  // Prints 'Hello, world!'.
  });
  worker.postMessage('Hello, world!');
} else {
  // When a message from the parent thread is received, send it back:
  parentPort.once('message', (message) => {
    parentPort.postMessage(message);
  });
}