simple-semaphore
v2.1.0
Published
Fast semaphore implementation with promise support.
Downloads
396
Readme
simple-semaphore
A fast semaphore implementation with promises.
Install
npm install simple-semaphore
API
class Semaphore {
/**
* Creates an instance of Semaphore.
* @param {number} [capacity=1] - Initial Semaphore value, should be non-negative.
*/
constructor(capacity = 1) {}
/**
* Attempt to acquire/consume semaphore value,
* @async
* @param {number} [n=1] - Wait cycles.
* @returns {Promise<void>} - The promise resolves when semaphore condition passes.
*/
wait(n = 1) { ... }
take(n = 1) { ... } /** @alias Semaphore.wait */
P(n = 1) { ... } /** @alias Semaphore.wait */
/**
* Resolve waiting promises or increment semaphore value.
* @param {number} [n=1] - Signal times.
*/
signal(n = 1) { ... }
release(n = 1) { ... } /** @alias Semaphore.signal */
V(n = 1) { ... } /** @alias Semaphore.signal */
/** Reject all promises on the waiting queue. */
rejectAll() { ... }
}
module.exports = Semaphore;
Example
See a full classic Producer-Consumer example in example.js
Require and Initialize
const Semaphore = require(`simple-semaphore`);
const sem_notFull = new Semaphore(10),
sem_notEmpty = new Semaphore(0);
Async/Await Style.
const produce = async () {
await sem_notFull.wait();
// produce...
sem_notEmpty.signal();
};
const consume = async () {
await sem_notEmpty.wait();
// produce...
sem_notFull.signal();
};
Promise Style.
const produce = () =>
sem_notFull.wait(10).then(() => {
// Wait 10 times before resolve.
// produce...
sem_notEmpty.signal(10); // Signals 10 times instantly.
});
const consume = () =>
sem_notEmpty.wait().then(() => {
// produce...
sem_notFull.signal();
});
Advanced hacks
sem_notFull._sem; // check the internal semaphore value
sem_notFull._queue.length; // check the internal waiting queue length
sem_notFull.rejectAll(); // reject and remove all promises from the waiting queue.
Changelog
2.1.0 / 2018-02-11
(Compatibility) With
async
keyword droped, this library can now be used with Node 6!2.0.1 / 2017-08-10
(Bugfix) Added rejection error messge.
2.0.0 / 2017-08-10
(Perfomance) Up to 10x faster by switching waiting queue to fastqueue.
- (New API)
rejectAll()
- Now the_queue
stores both[resolve, reject]
function references for every waiting promise. So promise fromwait()
may now reject ifrejectAll()
called.
(JSDoc) Style improvement.
1.1.0 / 2017-08-07
Added param
n
tosignal()
andwait()
for batch semaphore operation.1.0.0 / Initial Release.
Lisense
Licensed under MIT Copyright (c) 2017 Phoenix Song