1+ import Semaphore from 'semaphore-async-await'
2+
13interface Task {
24 priority : number
35 fn : Function
@@ -10,6 +12,8 @@ export class PrioritizedTaskExecutor {
1012 private currentPoolSize : number
1113 /** The task queue */
1214 private queue : Task [ ]
15+ /** The Lock */
16+ private lock : Semaphore
1317
1418 /**
1519 * Executes tasks up to maxPoolSize at a time, other items are put in a priority queue.
@@ -21,6 +25,7 @@ export class PrioritizedTaskExecutor {
2125 this . maxPoolSize = maxPoolSize
2226 this . currentPoolSize = 0
2327 this . queue = [ ]
28+ this . lock = new Semaphore ( 1 )
2429 }
2530
2631 /**
@@ -29,15 +34,18 @@ export class PrioritizedTaskExecutor {
2934 * @param priority The priority of the task
3035 * @param fn The function that accepts the callback, which must be called upon the task completion.
3136 */
32- execute ( priority : number , fn : Function ) {
37+ async execute ( priority : number , fn : Function ) {
38+ await this . lock . acquire ( )
3339 if ( this . currentPoolSize < this . maxPoolSize ) {
3440 this . currentPoolSize ++
35- fn ( ( ) => {
41+ fn ( async ( ) => {
42+ await this . lock . acquire ( )
3643 this . currentPoolSize --
3744 if ( this . queue . length > 0 ) {
3845 const item = this . queue . shift ( )
3946 this . execute ( item ! . priority , item ! . fn )
4047 }
48+ this . lock . signal ( )
4149 } )
4250 } else {
4351 if ( this . queue . length == 0 ) {
@@ -70,6 +78,7 @@ export class PrioritizedTaskExecutor {
7078 }
7179 }
7280 }
81+ this . lock . signal ( )
7382 }
7483
7584 /**
0 commit comments