Skip to content

Commit 1e9b8bf

Browse files
committed
Add CountingSemaphore with async/await contract
1 parent 7cc6eac commit 1e9b8bf

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

JavaScript/8-await-counting.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
5+
class CountingSemaphore {
6+
constructor(concurrency) {
7+
this.counter = concurrency;
8+
this.queue = [];
9+
}
10+
11+
enter() {
12+
return new Promise(resolve => {
13+
if (this.counter > 0) {
14+
this.counter--;
15+
resolve();
16+
return;
17+
}
18+
this.queue.push(resolve);
19+
});
20+
}
21+
22+
leave() {
23+
if (this.queue.length === 0) {
24+
this.counter++;
25+
return;
26+
}
27+
const resolve = this.queue.shift();
28+
resolve();
29+
}
30+
}
31+
32+
// Usage
33+
34+
const job = async task => {
35+
console.log('try enter', task);
36+
await semaphore.enter();
37+
console.log('enter', task);
38+
setTimeout(() => {
39+
semaphore.leave();
40+
console.log('leave', task);
41+
}, 1000);
42+
};
43+
44+
const semaphore = new CountingSemaphore(3);
45+
for (let i = 0; i < 100; i++) job(i);

0 commit comments

Comments
 (0)