mortice
Isomorphic read/write lock that works in single processes, node clusters and web workers
Table of contents
Install
$ npm i mortice
Features
- Reads occur concurrently
- Writes occur one at a time
- No reads occur while a write operation is in progress
- Locks can be created with different names
- Reads/writes can time out
Usage
import mortice from 'mortice'
import delay from 'delay'
const mutex = mortice('my-lock', {
timeout: 30000,
concurrency: 5,
singleProcess: false
})
Promise.all([
(async () => {
const release = await mutex.readLock()
try {
console.info('read 1')
} finally {
release()
}
})(),
(async () => {
const release = await mutex.readLock()
try {
console.info('read 2')
} finally {
release()
}
})(),
(async () => {
const release = await mutex.writeLock()
try {
await delay(1000)
console.info('write 1')
} finally {
release()
}
})(),
(async () => {
const release = await mutex.readLock()
try {
console.info('read 3')
} finally {
release()
}
})()
])
read 1
read 2
<small pause>
write 1
read 3
Browser
Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the observable-webworkers
module:
import mortice from 'mortice'
import observe from 'observable-webworkers'
const mutex = mortice()
const worker = new Worker('worker.js')
observe(worker)
import mortice from 'mortice'
import delay from 'delay'
const mutex = mortice()
let release = await mutex.readLock()
release()
release = await mutex.writeLock()
release()
License
Licensed under either of
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.