Web Locks API
implementation for Node.js based on
worker_threads,
Atomics,
SharedArrayBuffer,
asynchronous functions,
and queue.
See specification: wicg.github.io/web-locks/ and documentation: developer.mozilla.org/en-US/docs/Web/API/Lock
This implementation is a part of Metarhia technology stack, needed for the first pilot project of Node.js application server based on parallel programming and workload micro-isolation. Web Locks API is intended to be merged into Node.js in future.
- Simplest parallel programming primitive to solve a problem of data races and race conditions.
- Node.js and
worker_threadssupport. - Unified API for single-threaded asynchronous locks and multi-threaded locks.
- Exclusive lock mode (default).
AbortSignalsupport to cancel a lock request while waiting.- TypeScript typings included.
$ npm install web-locksconst { locks, AbortController } = require('web-locks');
// Exclusive lock (default)
await locks.request('Resource name', async (lock) => {
// use named resource; it is released after the callback settles
});
// Cancel a waiting request with AbortSignal
const controller = new AbortController();
const pending = locks.request(
'Resource name',
{ signal: controller.signal },
async () => {
// critical section
},
);
controller.abort(); // rejects pending with AbortErrorAttach workers so locks are coordinated across threads:
const { Worker } = require('worker_threads');
const { locks } = require('web-locks');
const worker = new Worker('./worker.js');
locks.attach(worker);name: stringβ resource nameoptions.mode?: 'exclusive'β onlyexclusiveis supportedoptions.signal?: AbortSignalβ abort waiting for the lockhandler: (lock: Lock) => void | Promise<void>β runs while holding the lock
Already-aborted signals reject immediately. Aborting while waiting cancels the
queued request and rejects with AbortError (or signal.reason when set).
held: Array<LockInfo>β currently held lockspending: Array<LockInfo>β queued lock requests
Registers a worker_threads.Worker for cross-thread lock coordination.
locks: LockManagerAbortController,AbortSignal,AbortErrorβ native when available, otherwise a small polyfill
This implementation of Web Locks API is MIT licensed.