https://github.com/rocicorp/lock
Provides Lock and RwLock synchronization primitives.
https://github.com/rocicorp/lock
Last synced: over 1 year ago
JSON representation
Provides Lock and RwLock synchronization primitives.
- Host: GitHub
- URL: https://github.com/rocicorp/lock
- Owner: rocicorp
- License: apache-2.0
- Created: 2022-03-14T19:45:49.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2024-12-09T22:30:29.000Z (over 1 year ago)
- Last Synced: 2025-04-02T15:05:52.021Z (over 1 year ago)
- Language: TypeScript
- Homepage: https://npmjs.com/package/@rocicorp/lock
- Size: 140 KB
- Stars: 14
- Watchers: 5
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Lock
Provides `Lock` and `RWLock` (read write lock) synchronization primitives for
protecting in-memory state across multiple tasks and/or microtasks.
# Installation
```
npm install @rocicorp/lock
```
# Usage
`Lock` is a mutex that can be used to synchronize access to a shared resource.
```ts
import {Lock} from '@rocicorp/lock';
const lock = new Lock();
async function f(n) {
const v = await lock.withLock(async () => {
await sleep(1000);
return n;
});
console.log(n);
}
void f(1);
void f(2);
// prints 1 at t=1000
// prints 2 at t=2000
```
`RWLock` is a read write lock. There can be mutlipe readers at the same time but only one writer at the same time.
```js
import {RWLock} from '@rocicorp/lock';
const rwLock = new RWLock();
async function read(n) {
const v = await lock.withRead(async () => {
await sleep(1000);
return n;
});
console.log('read', n);
}
async function write(n) {
const v = await lock.withWrite(async () => {
await sleep(1000);
return n;
});
console.log('write', n);
}
void read(1);
void write(2);
void read(3);
// prints read 1 at t=1000
// prints read 3 at t=1000
// prints write 2 at t=2000
```
Both `Lock` and `RWLock` expose non "with" methods (`lock`, `read` and `write`). These returns a promise to a release function that resolves when the lock is acquired. This is useful when you cannot wrap your code in a function like the examples above. When using these For example:
```js
const lock = new Lock();
const release = await lock.lock();
// here we got the lock
// do something
release();
```