@async-cancellables/async-lock
v2.2.0
Published
Asynchronous lock pool with priorities and cancellation support
Maintainers
Readme
Async Cancellables / AsyncLock
Asynchronous lock class allows to limit simultaneous resource access supporting prioritized access and cancellation tokens
Table of contents
Prerequisites
This project requires NodeJS (version 18 or later) and NPM.
Installation
To install and set up the library, run:
$ npm install @async-cancellables/async-stateExample
The following example downloads a list of files having no more than 2 concurrent downloads
import AsyncLock from '@async-cancellables/async-lock';
const lock = new AsyncLock(2);
async downloadFile(url) {
let ticket = await lock.waitOne();
try {
...
}
finally {
lock.release(ticket);
}
}
const files = await Promise.all(urls.map(url => downloadFile(lock, url)));API
Creating lock
new AsyncLock(totalSlots = 1) creates new lock with totalSlots of slots.
Waiting for slots
There are several wait methods:
waitOne(cancellationToken = null)waits for one slot to be availablewait(slotCount, cancellationToken = null)waits forslotCountslots to be availablewaitPrioritized(slotCount, priority, cancellationToken = null)waits with specified
All of them return ticket to be used for lock release. Default priority is 0, the higher it is the sooner wait method returns.
Releasing slots
release(ticket)releases slot count locked by any of the wait methods
Another way to release slots used by ticket is to call release() method of the ticket: ticket.release()
Accessing properties
totalSlotsgets or sets total slots of the lockusedSlotsgets slot count currently occupiedavailableSlotsget slot count currently availablewaitersPresentreturns presence of any waiters in the queuewaitersCountreturns count of waiters in the queue
Authors
- vuwuv - Initial work - vuwuv
License
[MIT License] © vuwuv
