File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 ) ;
You can’t perform that action at this time.
0 commit comments