Isomorphic read/write lock that works in single processes, node clusters and web workers
import mortice from 'mortice'
import delay from 'delay'
// the lock name & options objects are both optional
const mutex = mortice()
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
Mutexes are stored globally reference by name, this is so you can obtain the same lock from different contexts, including workers.
When a mutex is no longer required, the .finalize
function should be called
to remove any internal references to it.
import mortice from 'mortice'
const mutex = mortice()
// ...some time later
mutex.finalize()
$ npm i mortice
<script>
tagLoading this module through a script tag will make its exports available as Mortice
in the global namespace.
<script src="https://unpkg.com/mortice/dist/index.min.js"></script>
Licensed under either of
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.