simple-semaphore
A fast semaphore implementation with promises.
Install
npm install simple-semaphore
API
/** * Creates an instance of Semaphore. * @param */ {} /** * Attempt to acquire/consume semaphore value, * @async * @param * @returns */ { ... } { ... } /** @alias Semaphore.wait */ { ... } /** @alias Semaphore.wait */ /** * Resolve waiting promises or increment semaphore value. * @param */ { ... } { ... } /** @alias Semaphore.signal */ { ... } /** @alias Semaphore.signal */ /** Reject all promises on the waiting queue. */ { ... } moduleexports = Semaphore;
Example
See a full classic Producer-Consumer example in example.js
Require and Initialize
const Semaphore = ; const sem_notFull = 10 sem_notEmpty = 0;
Async/Await Style.
const produce = { await sem_notFull; // produce... sem_notEmpty;}; const consume = { await sem_notEmpty; // produce... sem_notFull;};
Promise Style.
const produce = sem_notFull; const consume = sem_notEmpty;
Advanced hacks
sem_notFull_sem; // check the internal semaphore valuesem_notFull_queuelength; // check the internal waiting queue lengthsem_notFull; // 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