feat: add tasks stealing algorithm
[poolifier.git] / src / pools / worker-node.ts
index d7f96e6499522f79d45035150f56b24c392eb2e5..b539cabd9af018bd71c8c8e27eba63eab755333a 100644 (file)
@@ -30,6 +30,8 @@ implements IWorkerNode<Worker, Data> {
   public usage: WorkerUsage
   /** @inheritdoc */
   public tasksQueueBackPressureSize: number
+  /** @inheritdoc */
+  public onBackPressure?: (workerId: number) => void
   private readonly taskFunctionsUsage: Map<string, WorkerUsage>
   private readonly tasksQueue: Deque<Task<Data>>
 
@@ -90,7 +92,20 @@ implements IWorkerNode<Worker, Data> {
 
   /** @inheritdoc */
   public enqueueTask (task: Task<Data>): number {
-    return this.tasksQueue.push(task)
+    const tasksQueueSize = this.tasksQueue.push(task)
+    if (this.onBackPressure != null && this.hasBackPressure()) {
+      this.once(this.onBackPressure)(this.info.id as number)
+    }
+    return tasksQueueSize
+  }
+
+  /** @inheritdoc */
+  public unshiftTask (task: Task<Data>): number {
+    const tasksQueueSize = this.tasksQueue.unshift(task)
+    if (this.onBackPressure != null && this.hasBackPressure()) {
+      this.once(this.onBackPressure)(this.info.id as number)
+    }
+    return tasksQueueSize
   }
 
   /** @inheritdoc */
@@ -98,6 +113,11 @@ implements IWorkerNode<Worker, Data> {
     return this.tasksQueue.shift()
   }
 
+  /** @inheritdoc */
+  public popTask (): Task<Data> | undefined {
+    return this.tasksQueue.pop()
+  }
+
   /** @inheritdoc */
   public clearTasksQueue (): void {
     this.tasksQueue.clear()
@@ -251,4 +271,25 @@ implements IWorkerNode<Worker, Data> {
       return worker.id
     }
   }
+
+  /**
+   * Executes a function once at a time.
+   */
+
+  private once (
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    fn: (...args: any[]) => void,
+    context = this
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  ): (...args: any[]) => void {
+    let called = false
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    return function (...args: any[]): void {
+      if (!called) {
+        called = true
+        fn.apply(context, args)
+        called = false
+      }
+    }
+  }
 }