source: node_modules/es-toolkit/dist/promise/semaphore.mjs

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 678 bytes
Line 
1class Semaphore {
2 capacity;
3 available;
4 deferredTasks = [];
5 constructor(capacity) {
6 this.capacity = capacity;
7 this.available = capacity;
8 }
9 async acquire() {
10 if (this.available > 0) {
11 this.available--;
12 return;
13 }
14 return new Promise(resolve => {
15 this.deferredTasks.push(resolve);
16 });
17 }
18 release() {
19 const deferredTask = this.deferredTasks.shift();
20 if (deferredTask != null) {
21 deferredTask();
22 return;
23 }
24 if (this.available < this.capacity) {
25 this.available++;
26 }
27 }
28}
29
30export { Semaphore };
Note: See TracBrowser for help on using the repository browser.