Skip to content

Latest commit

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Mutex

Cross-process named mutex for Node.js using file locks (and not redis!).

npm install https://github.com/Perennials/mutex-node

This is port from https://github.com/Perennials/providerkit-core-php/blob/master/src/sync/Mutex.php.

Example

varMutex=require('Mutex');varmutex=newMutex('should_happen_one_at_a_time');mutex.lock();// .. do something and rest assured this is the only process doing itmutex.unlock();

API

Constructor

Constructs a mutex.

  • It starts in unlocked state.
  • The name you provide goes as a file name with extension .mutex in the system temporary directory, so don't get too fancy with the name.
  • Consider this will only work if the processes that are to mutually exclude each other use the same temp dir.
  • If .unlock() is not properly called the lock file will remain in the temp directory, which will not affect future locking, but just leave trash behind.
newMutex(name:String);

.lock()

Acquires the lock without waiting. Meaning if the lock is busy the function will fail immediately.

  • If the function works in sync or async mode is determined by the presence of a callback argument.
  • In sync mode the function will throw on errors.
  • The lock can not outlive the process life time, even if it is not released.
.lock(callback:function(err:Error|null)|undefined) : Boolean;

.waitLock()

Acquires the lock waiting for it to become available if necessary. This waiting does not relate to the asyncness of the function.

  • If the function works in sync or async mode is determined by the presence of a callback argument.
  • In sync mode the function may possibly block for very long time until the lock becomes available.
.waitLock(callback:function(err:Error|null)|undefined) : Boolean;

.tryLock()

Acquires the lock without waiting and without throwing.

  • If the function works in sync or async mode is determined by the presence of a callback argument.
  • In sync mode the function will not throw but just return false.
.tryLock(callback:function(err:Error|null)|undefined) : Boolean;

.unlock()

Releases the lock.

  • If the function works in sync or async mode is determined by the presence of a callback argument.
  • If this function is not properly called the lock file will remain in the temp directory, which will not affect future locking, but just leave trash behind.
.unlock(callback:function(err:Error|null)|undefined) : Boolean;

.isLocked()

Checks if the mutex is locked.

.isLocked() : Boolean;

Authors

Borislav Peev (borislav.asdf at gmail dot com)

About

Cross-process named mutex for Node.js using file locks (and not redis!).

Resources

Stars

15 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages