@poccomaxa/semaphore
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

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.

Readme

Keywords

Package Sidebar

Install

npm i @poccomaxa/semaphore

Weekly Downloads

63

Version

2.0.2

License

ISC

Unpacked Size

7.29 kB

Total Files

10

Last publish

Collaborators

  • poccomaxa