diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 7de28b99e403dc..faa42bf4b1cad7 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -274,6 +274,109 @@ if (isMainThread) { } ``` +## `worker.locks` + + +> Stability: 1 - Experimental + +* {LockManager} + +An instance of a [`LockManager`][]. + +### Class: `Lock` + + +The Lock interface provides the name and mode of a previously requested lock, +which is received in the callback to [`locks.request()`][]. + +#### `lock.name` + + +* {string} + +The name of this lock. + +#### `lock.mode` + + +* {string} + +The mode of this lock. Either `shared` or `exclusive`. + +### Class: `LockManager` + + +The `LockManager` interface provides methods for requesting a new [`Lock`][] +object and querying for an existing `Lock` object. To get an instance of +`LockManager`, call `worker_threads.locks`. + +This implementation matches the [browser `LockManager`][] API. + +#### `locks.request(name[, options], callback)` + + +* `name` {string} +* `options` {Object} + * `mode` {string} Either `'exclusive'` or `'shared'`. **Default:** + `'exclusive'`. + * `ifAvailable` {boolean} If `true`, the lock request will only be + granted if it is not already held. If it cannot be granted, the + callback will be invoked with `null` instead of a `Lock` instance. + **Default:** `false`. + * `steal` {boolean} If `true`, then any held locks with the same name will be + released, and the request will be granted, preempting any queued requests + for it. **Default:** `false`. + * `signal` {AbortSignal} A signal that can be used to abort pending, not-yet + acquired lock requests. +* `callback` {Function} The function to be invoked while the lock is acquired. + The lock will be released when the function ends, or if the function returns + a promise, when that promise settles. +* Returns: {Promise} + +Requests a [`Lock`][] object with parameters specifying its name and +characteristics. + +```js +worker_threads.locks.request('my_resource', async (lock) => { + // The lock was granted. +}).then(() => { + // The lock is released here. +}); +``` + +#### `locks.query()` + + +* Returns: {Promise} + +Returns a Promise that resolves with a [`LockManagerSnapshot`][] which contains +information about held and pending locks. + +```js +worker_threads.locks.query().then((state) => { + state.held.forEach((lock) => { + console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); + }); + state.pending.forEach((request) => { + console.log(`requested lock: name ${request.name}, mode ${request.mode}`); + }); +}); +``` + ## Class: `BroadcastChannel extends EventTarget`