A counting semaphore based on Java's Concurrent Semaphore.
Install the module via npm:
npm install ts-async-semaphore
// fairness false
import { Semaphore } from 'ts-async-semaphore';
const semaphore = new Semaphore(0);
semaphore.acquire(2).then(() => {
console.log('Hello');
});
semaphore.acquire().then(() => {
console.log('World');
semaphore.release(2);
});
setTimeout(function () {
semaphore.release();
}, 2000);
// fairness true
import { Semaphore } from 'ts-async-semaphore';
const semaphore = new Semaphore(0, true);
semaphore.acquire(2).then(() => {
console.log('Hello');
});
semaphore.acquire().then(() => {
console.log('World');
});
semaphore.release(1);
setTimeout(function () {
semaphore.release(2);
}, 2000);
import { Semaphore } from 'ts-async-semaphore';
const semaphore = new Semaphore(0, true);
semaphore.tryAcquire(1, 50).then((val) => {
console.log(`Acquire ${val ? 'success' : 'fail'}`);
});
permits: Integer
Initial available permits of semaphore. Default: 0
.
fairness: Boolean
Fairness of semaphore. If set to true
, a FIFO rules applied, else, look on each acquirers permit value.
Returns the current number of permits available in this semaphore.
Returns: number
Acquires the given number of permits from this semaphore.
permits: number
The number of permits to acquire. Default: 0
.
Returns an estimate of the number of acquirers waiting to acquire.
Returns: Function[]
Returns an estimate of the number of acquirers waiting to acquire.
Returns: number
Releases the given number of permits, returning them to the semaphore.
permits: number
The number of permits to release. Default: 0
.
Acquires and returns all permits that are immediately available.
Returns: number
Shrinks the number of available permits by the indicated reduction.
permits: number
The number of permits to remove.
Acquires the given number of permits from this semaphore.
permits: number
The number of permits to acquire. Default: 0
.
timeoutMs: number
The timeout after which the acquire will fail
Returns: Boolean
Promise true
if success, false
false if fail