From c7cf8d9b749fea2148e823e670bacd4f02009d7d Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Thu, 18 Apr 2019 00:56:57 +0200 Subject: [PATCH] worker: add ability to unshift message from MessagePort In combination with Atomics, this makes it possible to implement generic synchronous functionality, e.g. `importScript()`, in Workers purely by communicating with other threads. This is a continuation of https://github.com/nodejs/node/pull/26686, where a preference for a solution was voiced that allowed reading individual messages, rather than emitting all messages through events. PR-URL: https://github.com/nodejs/node/pull/27294 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Gus Caplan Reviewed-By: Ruben Bridgewater --- doc/api/worker_threads.md | 28 +++++ lib/internal/worker/io.js | 11 +- lib/worker_threads.js | 2 + src/env.h | 1 + src/node_messaging.cc | 118 +++++++++++------- src/node_messaging.h | 3 + ...est-worker-message-port-receive-message.js | 25 ++++ 7 files changed, 139 insertions(+), 49 deletions(-) create mode 100644 test/parallel/test-worker-message-port-receive-message.js diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 77afaaec9c5cc3..3c36a0a03cfdb9 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -125,6 +125,34 @@ if (isMainThread) { } ``` +## worker.receiveMessageOnPort(port) + + +* `port` {MessagePort} + +* Returns: {Object|undefined} + +Receive a single message from a given `MessagePort`. If no message is available, +`undefined` is returned, otherwise an object with a single `message` property +that contains the message payload, corresponding to the oldest message in the +`MessagePort`’s queue. + +```js +const { MessageChannel, receiveMessageOnPort } = require('worker_threads'); +const { port1, port2 } = new MessageChannel(); +port1.postMessage({ hello: 'world' }); + +console.log(receiveMessageOnPort(port2)); +// Prints: { message: { hello: 'world' } } +console.log(receiveMessageOnPort(port2)); +// Prints: undefined +``` + +When this function is used, no `'message'` event will be emitted and the +`onmessage` listener will not be invoked. + ## worker.SHARE_ENV