From 9d112bd598dce0e9b2930dc5af3c738f63b9763f Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 15 Mar 2019 18:21:06 +0100 Subject: [PATCH] worker: allow synchronously draining message ports In combination with Atomics, this makes it possible to implement generic synchronous functionality, e.g. `importScript()`, in Workers purely by communicating with other threads. --- doc/api/worker_threads.md | 20 +++++++++++++++++++ lib/internal/worker.js | 1 + lib/worker_threads.js | 2 ++ .../test-worker-message-port-drain-manual.js | 19 ++++++++++++++++++ 4 files changed, 42 insertions(+) create mode 100644 test/parallel/test-worker-message-port-drain-manual.js diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 16787723c6e57e..a545febf3d2565 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -49,6 +49,26 @@ The above example spawns a Worker thread for each `parse()` call. In actual practice, use a pool of Workers instead for these kinds of tasks. Otherwise, the overhead of creating Workers would likely exceed their benefit. +## worker.drainMessagePort(port) + + +* `port` {MessagePort} + +Make `port` emit all currently pending messages synchronously. + +```js +const { MessageChannel, drainMessagePort } = require('worker_threads'); +const { port1, port2 } = new MessageChannel(); + +port1.postMessage({ hello: 'world' }); +port2.once('message', (message) => console.log(message)); + +drainMessagePort(port2); +console.log('done emitting messages'); // This is printed *after* the message. +``` + ## worker.isMainThread