# node:worker_threads

> How Elide supports Node's `worker_threads`: Worker, parentPort, MessageChannel and the other exports, which Worker options it reads, and other differences.

`node:worker_threads` runs scripts on separate threads with
[Node's `worker_threads`](https://nodejs.org/api/worker_threads.html) API. `elide run` does not exit while a worker
runs.

## Example

```js
// worker.mjs
import { Worker } from "node:worker_threads";

const source = `
  const { parentPort, workerData } = require("node:worker_threads");
  parentPort.postMessage(workerData.map((n) => n * n));
`;
const worker = new Worker(source, { eval: true, workerData: [1, 2, 3] });
worker.on("message", (squares) => {
  console.log("from worker:", squares.join(" "));
  worker.terminate();
});
worker.on("exit", (code) => console.log("worker exited", code));
```

`elide run worker.mjs` prints:

```text
from worker: 1 4 9
worker exited 0
```

## Differences from Node

- `new Worker` reads only the `workerData`, `eval`, `transferList`, and `env` options.
- A missing script file emits `error` with code `ERR_WORKER_PATH`.
- `stdout` and `stderr` are always inherited from the parent.
- `resourceLimits` is `{}`.
- Posting a `ReadableStream` throws `DataCloneError`.
- Posting to a terminated worker is a no-op.
- `--limit=workers=COUNT` limits how many workers a script may start; see [Sandbox](https://elide.help/docs/sandbox).

## Samples

- [Worker threads](https://elide.help/docs/code-samples#worker-threads)
- [Limit workers](https://elide.help/docs/code-samples#limit-workers)

<!-- api-reference:start e349d4a46a33 -->
## Reference

**Status:** Partial · 105 of 128 suite tests pass (82.0%)

### `worker_threads` exports

`BroadcastChannel`, `MessageChannel`, `MessagePort`, `Worker`, `getEnvironmentData`, `isInternalThread`, `isMainThread`, `isMarkedAsUntransferable`, `markAsUncloneable`, `markAsUntransferable`, `moveMessagePortToContext`, `parentPort`, `postMessageToThread`, `receiveMessageOnPort`, `resourceLimits`, `setEnvironmentData`, `threadId`, `threadName`, `workerData`, 1 constants such as `SHARE_ENV`

### Not implemented

`locks`.

**Tests:** [node-api `node:worker-threads`](https://github.com/elide-dev/testsuite/blob/main/reports/1.6.0%2B6e718933f/4cbcae6c33a8/node-api/node-api.md): 105 pass, 22 fail, 1 error, 11 skipped. Failing: `test-worker-cleanup-handles.js`, `test-worker-cpu-profile.js`, `test-worker-data-url.js`, `test-worker-eval-typescript.js`, `test-worker-exit-heapsnapshot.js`, `test-worker-heap-profile.js`, `test-worker-heap-snapshot.js`, `test-worker-heapdump-failure.js`, and 15 more.
<!-- api-reference:end -->
