A memory-based read-write lock for Node.js.
npm install memory-lockasync chain with the callback, to make sure that a certain flow is "synchronized".
var MemoryLock = require('memory-lock');,
var lock = MemoryLock().
name argument if you want to retrieve an existing lock with the same name.
priority argument to set read/write priority.
MemoryLock.Priority.UNSPECIFIED (default), MemoryLock.Priority.READ, MemoryLock.Priority.WRITE.
readLock([timeout, ][callback]):boolean | Acquire a read lock (timeout defaults to -1)
writeUnlock([timeout, ][callback]):boolean | Acquire a write lock (timeout defaults to -1)
readUnlock():boolean | Release a read lock
writeUnlock():boolean | Release a write lock
upgradeToWriteLock():boolean | Try to upgrade a read lock to a write lock. It takes place immediately, and returns true/false as a success value.
downgradeToReadLock():boolean | Try to downgrade a write lock to a read lock. It takes place immediately, and returns true/false as a success value.
priority:MemoryLock.Priority | Get/set the lock's priority at any time
currentReadLocks:Number | Get the number of current read locks
hasWriteLock:Number | Returns true if there's a write lock
pendingReadLocks:Number | Get the number of pending read locks
pendingWriteLocks:Number | Get the number of pending write locks
0 will fail immediately in case there's no way to immediately acquire the lock.
false and still it will be acquired later automatically, as long as the timeout has not passed yet.
javascript
var MemoryLock = require('memory-lock');
.
.
.
async.series([
function (callback) {
locker.writeLock(15000, callback);
},
.
.
.
function (callback) {
...
// We may not want to unlock here, as it could be skipped if there was an error in the async chain
// locker.writeUnlock();
...
}
],
function finishLine (error) {
...
// Make sure to unlock even if there was an error in the async chain
locker.writeUnlock();
...
}
);
``