From b62c08b28413118b7406ff5be005c42c42958bb2 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 22 Feb 2021 16:22:17 -0800 Subject: [PATCH] worker: add setEnvironmentData/getEnvironmentData These APIs allow arbitrary, cloneable JavaScript values to be set and passed to all new Worker instances spawned from the current context. It is similar to `workerData` except that environment data is set independently of the `new Worker()` constructor, and the the value is passed automatically to all new Workers. This is a *partial* fix of https://github.com/nodejs/node/issues/30992 but does not implement a complete fix. Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/37486 Reviewed-By: Anna Henningsen Reviewed-By: Gireesh Punathil Reviewed-By: Darshan Sen --- doc/api/worker_threads.md | 49 ++++++++++++++++++++ lib/internal/main/worker_thread.js | 3 ++ lib/internal/worker.js | 25 ++++++++++ lib/worker_threads.js | 4 ++ test/parallel/test-worker-environmentdata.js | 33 +++++++++++++ 5 files changed, 114 insertions(+) create mode 100644 test/parallel/test-worker-environmentdata.js diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 7942788df58e5d..c8fc33750ee484 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -61,6 +61,38 @@ Worker threads inherit non-process-specific options by default. Refer to [`Worker constructor options`][] to know how to customize worker thread options, specifically `argv` and `execArgv` options. +## `worker.getEnvironmentData(key)` + + +> Stability: 1 - Experimental + +* `key` {any} Any arbitrary, cloneable JavaScript value that can be used as a + {Map} key. +* Returns: {any} + +Within a worker thread, `worker.getEnvironmentData()` returns a clone +of data passed to the spawning thread's `worker.setEnvironmentData()`. +Every new `Worker` receives its own copy of the environment data +automatically. + +```js +const { + Worker, + isMainThread, + setEnvironmentData, + getEnvironmentData, +} = require('worker_threads'); + +if (isMainThread) { + setEnvironmentData('Hello', 'World!'); + const worker = new Worker(__filename); +} else { + console.log(getEnvironmentData('Hello')); // Prints 'World!'. +} +``` + ## `worker.isMainThread` + +> Stability: 1 - Experimental + +* `key` {any} Any arbitrary, cloneable JavaScript value that can be used as a + {Map} key. +* `value` {any} Any arbitrary, cloneable JavaScript value that will be cloned + and passed automatically to all new `Worker` instances. If `value` is passed + as `undefined`, any previously set value for the `key` will be deleted. + +The `worker.setEnvironmentData()` API sets the content of +`worker.getEnvironmentData()` in the current thread and all new `Worker` +instances spawned from the current context. + ## `worker.threadId`