Stability: 1Experimental
Attributes
An instance of a LockManager that can be used to coordinate
access to resources that may be shared across multiple threads within the same
process. The API mirrors the semantics of the
browser LockManager
The Lock interface provides information about a lock that has been granted via
locks.request()
Attributes
The name of the lock.
Attributes
The mode of the lock. Either shared or exclusive.
The LockManager interface provides methods for requesting and introspecting
locks. To obtain a LockManager instance use
import { locks } from 'node:worker_threads';
const { locks } = require('node:worker_threads');
This implementation matches the browser LockManager API.
locks.request(name, options?, callback): Promise
Attributes
name:
stringoptions:
Objectmode?:
stringEither
'exclusive' or 'shared'. Default: 'exclusive'.ifAvailable?:
booleanIf
true, the request will only be granted if the
lock is not already held. If it cannot be granted, callback will be
invoked with null instead of a Lock instance. Default: false.steal?:
booleanIf
true, any existing locks with the same name are
released and the request is granted immediately, pre-empting any queued
requests. Default: false.signal:
AbortSignalthat can be used to abort a
pending (but not yet granted) lock request.
callback:
FunctionInvoked once the lock is granted (or immediately with
null if ifAvailable is true and the lock is unavailable). The lock is
released automatically when the function returns, or—if the function returns
a promise—when that promise settles.Returns:
PromiseResolves once the lock has been released.
import { locks } from 'node:worker_threads'; await locks.request('my_resource', async (lock) => { // The lock has been acquired. }); // The lock has been released here.
const { locks } = require('node:worker_threads'); locks.request('my_resource', async (lock) => { // The lock has been acquired. }).then(() => { // The lock has been released here. });
locks.query(): Promise
Returns:
PromiseResolves with a LockManagerSnapshot describing the currently held and pending
locks for the current process.
import { locks } from 'node:worker_threads'; const snapshot = await locks.query(); for (const lock of snapshot.held) { console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); } for (const pending of snapshot.pending) { console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`); }
const { locks } = require('node:worker_threads'); locks.query().then((snapshot) => { for (const lock of snapshot.held) { console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); } for (const pending of snapshot.pending) { console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`); } });