shmutex
Simple shared mutex (or read/write lock) for JS. Lock lifecycle can be encapsulated by a function call or a promise.
Clients can request either an "exclusive" (write) or "shared" (read) lock. If an exclusive lock is held, no other locks can be acquired. If any read lock is held, other read locks can be acquired but no exclusive locks can be acquired.
API:
lock(func, exclusive = false)
- Requests lock and fires
func
when the lock is acquired. Iffunc
returns a thenable, the lock will be released when the thenable resolves. Otherwise, the lock is released whenfunc
returns. Returns a promise for the result offunc
.
- Requests lock and fires
read(func)
- Alias for
lock(func)
- Alias for
write(func)
- Alias for
lock(func, true)
- Alias for
Example:
"use strict"; const shmutex = q = ; let myShmutex = sharedString = ""; let startMs = Date; ;;;;; ; // Output:// Write #1 (5004ms): oh// Read #3 (7526ms): oh// Read #2 (10028ms): oh// Read #1 (15027ms): oh// Write #2 (20029ms): hi// Read #4 (21030ms): hi// done. { return myShmutex;} { return myShmutex;} { let elapsed = Date - startMs; console;}