Skip to content

workers: make Worker async disposable #58385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions doc/api/worker_threads.md
Original file line number Diff line number Diff line change
Expand Up @@ -1861,6 +1861,21 @@ Calling `unref()` on a worker allows the thread to exit if this is the only
active handle in the event system. If the worker is already `unref()`ed calling
`unref()` again has no effect.

### `worker[Symbol.asyncDispose]()`

<!-- YAML
added: REPLACEME
-->

Calls [`worker.terminate()`][] when the dispose scope is exited.

```js
async function example() {
await using worker = new Worker('for (;;) {}', { eval: true });
// Worker is automatically terminate when the scope is exited.
}
```

## Notes

### Synchronous blocking of stdio
Expand Down
5 changes: 5 additions & 0 deletions lib/internal/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const {
String,
StringPrototypeTrim,
Symbol,
SymbolAsyncDispose,
SymbolFor,
TypedArrayPrototypeFill,
Uint32Array,
Expand Down Expand Up @@ -407,6 +408,10 @@ class Worker extends EventEmitter {
});
}

async [SymbolAsyncDispose]() {
await this.terminate();
}

ref() {
if (this[kHandle] === null) return;

Expand Down
10 changes: 10 additions & 0 deletions test/parallel/test-worker-dispose.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as common from '../common/index.mjs';
import { Worker } from 'node:worker_threads';

let w;
{
// Verifies that the worker is async disposable
await using worker = new Worker('for(;;) {}', { eval: true });
w = worker;
w.on('exit', common.mustCall());
}
Comment on lines +4 to +10
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: was w meant to be checked after the scope? If not, we don't really need it.

Suggested change
let w;
{
// Verifies that the worker is async disposable
await using worker = new Worker('for(;;) {}', { eval: true });
w = worker;
w.on('exit', common.mustCall());
}
{
// Verifies that the worker is async disposable
await using worker = new Worker('for(;;) {}', { eval: true });
worker.on('exit', common.mustCall());
}

Loading