On this page

P

worker_threads.locks

History
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

C

Lock

History

The Lock interface provides information about a lock that has been granted via locks.request()

P

lock.name

History
Attributes

The name of the lock.

P

lock.mode

History
Attributes

The mode of the lock. Either shared or exclusive.

C

LockManager

History

The LockManager interface provides methods for requesting and introspecting locks. To obtain a LockManager instance use

This implementation matches the browser LockManager API.

M

locks.request

History
locks.request(name, options?, callback): Promise
Attributes
name:string
options:Object
mode?:string
Either 'exclusive' or 'shared'. Default: 'exclusive'.
ifAvailable?:boolean
If 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?:boolean
If true, any existing locks with the same name are released and the request is granted immediately, pre-empting any queued requests. Default: false.
that can be used to abort a pending (but not yet granted) lock request.
callback:Function
Invoked 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:Promise
Resolves 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.
});
M

locks.query

History
locks.query(): Promise
Returns:Promise

Resolves 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}`);
  }
});