Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/node-libraries/semaphore
https://github.com/node-libraries/semaphore
Last synced: about 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/node-libraries/semaphore
- Owner: node-libraries
- Created: 2023-06-23T05:03:52.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2023-12-06T11:51:05.000Z (about 1 year ago)
- Last Synced: 2024-10-13T08:45:14.092Z (3 months ago)
- Language: TypeScript
- Size: 11.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# @node-libraries/semaphore
Implement virtual semaphore for asynchronous processing
## usage
```ts
// Importing packages
import { semaphore } from "@node-libraries/semaphore";
// Instance Creation
const s = semaphore();
// Synchronization Lock
await s.acquire();
// Synchronization lock release
s.release();
// Wait until all locks are unlocked.
await s.all();
``````ts
// Specify maximum number of parallels
const s = semaphore(5);
```## example
```ts
import { semaphore } from "@node-libraries/semaphore";const f = (value: string) =>
new Promise((resolve) => {
console.timeLog("debug", value);
setTimeout(resolve, 1000);
});const main = async () => {
console.time("debug");
const s = semaphore();
["A", "B", "C", "D", "E"].forEach(async (v) => {
await s.acquire();
await f(v);
s.release();
});
await s.all(); // Wait for everything to be finished.
console.timeLog("debug", "end");
};
main();/* Result
debug: 0.197ms A
debug: 1.014s B
debug: 2.027s C
debug: 3.039s D
debug: 4.040s E
debug: 5.050s end
*/
``````ts
import { semaphore } from "@node-libraries/semaphore";const f = (value: string) =>
new Promise((resolve) => {
console.timeLog("debug", value);
setTimeout(resolve, 1000);
});const main = async () => {
console.time("debug");
const s = semaphore(2);
["A", "B", "C", "D", "E"].forEach(async (v) => {
await s.acquire();
await f(v);
s.release();
});
await s.all(); // Wait for everything to be finished.
console.timeLog("debug", "end");
};
main();/* Result
debug: 0.19ms A
debug: 1.826ms B
debug: 1.005s C
debug: 1.005s D
debug: 2.012s E
debug: 3.028s end
*/
```