0.2.1 • Published 8 years ago

snap-mutex v0.2.1

Weekly downloads
27
License
ISC
Repository
-
Last release
8 years ago

snap-mutex

A promise based mutex micro-library for JavaScript. API is optimized for async functions.

Build Status Coverage Status

Installation

  $ npm install --save snap-mutex

Example

const Mutex = require('snap-mutex');

const myMutex = new Mutex();

async function onlyOneAtTime() {
  let lock;

  try {
    // Try to get the lock
    lock = await myMutex.acquire({ timeout: 60000 }); // 60 seconds
  } catch (e) {
    // Failed to acquire the lock
    throw new Error('Mutex locking timeout');
  }

  try {
    console.log('Got the lock!');
    // await doStuff();
  } finally {
    // Release the lock even if the doStuff() throws an exception
    lock.release();
  }
}

// Now onlyOneAtTime() can be called freely
for (let i = 0; i < 9; i++) {
  onlyOneAtTime();
}

Remember to put try ... finally around the critical section so that the lock gets released in all cases.

0.2.1

8 years ago

0.2.0

8 years ago

0.1.1

8 years ago

0.1.0

8 years ago