if warnAfterMs is set, the lock will emit a warning if a call to lock.acquire() tok more than warnAfterMs` milliseconds.
Optionalprops: { warnAfterMs?: number }Weather the lock is currently taken. Because javascript is single-threaded, it is safe to do e.g.:
if (!lock.locked) {
lock.acquire()
// do something
lock.release()
}
without awaiting the lock.acquire().
Wait until no other async thread holds a lock, then returns a lock.
Once the lock is held, all other threads that call acquire() will have to wait until
the lock is released.
Release the lock with lock.release().
Example:
const lock = new AsyncLock()
...
const l = await lock.acquire()
// do stuff
l.release()
Execute a function after acquiring a lock, and release the lock after the function is done.
Example:
const v = await lock.runAcquired(() => {
// do something
return 42
})
This function is safe against exceptions. If the function throws an exception, the lock is released before the exception is thrown.
A lock to lock a resource in an async environment.
Await
lock.acquire()to wait until the lock is released before code is continued.Note that this is not a "real" thread lock, it won't put the thread to sleep differently than any other
awaitcall. This means that there's very little performance overhead incurred simply by acquiring a lock. Tests on my machine show that acquiring a lock takes in order of about 100 us.