https://github.com/iplaylf2/async-monitor
Provides a mechanism that synchronizes access to objects.
https://github.com/iplaylf2/async-monitor
lock reentrant typescript
Last synced: 2 months ago
JSON representation
Provides a mechanism that synchronizes access to objects.
- Host: GitHub
- URL: https://github.com/iplaylf2/async-monitor
- Owner: iplaylf2
- License: bsd-3-clause
- Created: 2023-11-09T07:51:32.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2023-12-18T08:57:04.000Z (over 1 year ago)
- Last Synced: 2025-01-23T01:15:58.517Z (4 months ago)
- Topics: lock, reentrant, typescript
- Language: TypeScript
- Homepage:
- Size: 43 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# async-monitor
`async-monitor` is a nodejs library that provides a simple way to synchronize access to shared objects in asynchronous code blocks.
It is inspired by the [Monitor](https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor) class in .NET, which allows multiple threads to acquire and release exclusive locks on resources.
Since async-monitor uses AsyncLocalStorage and Symbol.dispose internally, it can only be used in nodejs 20+ environments.
## usage
```typescript
import { enter } from "async-monitor";async function delay(timeout: number) {
await new Promise((resolve) => {
setTimeout(resolve, timeout);
});
}let foo = 0;
void (async () => {
while (true) {
await enter(233, async (section) => {
console.log("while 1");section.pulseAll();
await section.wait();const value = foo;
await delay(500);foo = value + 1;
console.log(`while 1: ${foo}`);
});
}
})();void (async () => {
while (true) {
await enter(233, async (section) => {
console.log("while 2");section.pulseAll();
await section.wait();const value = foo;
await delay(500);console.log("to reenter");
await enter(233, () => {
console.log("reenter");
});foo = value + 1;
console.log(`while 2: ${foo}`);
});
}
})();
```