@poccomaxa/semaphore
v2.0.2
Published
semaphore
Downloads
307
Readme
Semaphore
Limit simultaneous access to a resource.
Install
npm install @poccomaxa/semaphore
Using
Interface
/**
* @param n {number=1}
* @constructor
*/
const Semaphore = require('@poccomaxa/semaphore');
/** @return {Promise} */
async Semaphore.enter();
/**
* leave after delay
* @param delay {number=0} milliseconds
* */
Semaphore.leave(delay);
example
const Semaphore = require("@poccomaxa/semaphore");
let semaphore = new Semaphore(2);
function expensive_operation(callback) {
setTimeout(callback, 1000);
}
async function fn() {
await semaphore.enter();
expensive_operation(function () {
console.log(Date.now());
semaphore.leave();
});
}
fn();
fn();
fn();
fn();
/* Output:
* 1483205883425
* 1483205883434
* 1483205884437
* 1483205884437
*/
Caution
Don't forget to call leave
method after enter
to avoid semaphore leaking.