import { MessageChannel } from 'node:worker_threads'
import { CircularArray } from '../circular-array'
import type { Task } from '../utility-types'
-import { DEFAULT_TASK_NAME } from '../utils'
+import { DEFAULT_TASK_NAME, once } from '../utils'
import { Deque } from '../deque'
import {
type IWorker,
public tasksQueueBackPressureSize: number
/** @inheritdoc */
public onBackPressure?: (workerId: number) => void
+ /** @inheritdoc */
+ public onEmptyQueue?: (workerId: number) => void
private readonly taskFunctionsUsage: Map<string, WorkerUsage>
private readonly tasksQueue: Deque<Task<Data>>
return this.tasksQueue.size
}
- /**
- * Tasks queue maximum size.
- *
- * @returns The tasks queue maximum size.
- */
- private tasksQueueMaxSize (): number {
- return this.tasksQueue.maxSize
- }
-
/** @inheritdoc */
public enqueueTask (task: Task<Data>): number {
const tasksQueueSize = this.tasksQueue.push(task)
if (this.onBackPressure != null && this.hasBackPressure()) {
- this.once(this.onBackPressure)(this.info.id as number)
+ once(this.onBackPressure, this)(this.info.id as number)
}
return tasksQueueSize
}
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)
+ once(this.onBackPressure, this)(this.info.id as number)
}
return tasksQueueSize
}
/** @inheritdoc */
public dequeueTask (): Task<Data> | undefined {
- return this.tasksQueue.shift()
+ const task = this.tasksQueue.shift()
+ if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
+ once(this.onEmptyQueue, this)(this.info.id as number)
+ }
+ return task
}
/** @inheritdoc */
public popTask (): Task<Data> | undefined {
- return this.tasksQueue.pop()
+ const task = this.tasksQueue.pop()
+ if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
+ once(this.onEmptyQueue, this)(this.info.id as number)
+ }
+ return task
}
/** @inheritdoc */
private initWorkerUsage (): WorkerUsage {
const getTasksQueueSize = (): number => {
- return this.tasksQueueSize()
+ return this.tasksQueue.size
}
const getTasksQueueMaxSize = (): number => {
- return this.tasksQueueMaxSize()
+ return this.tasksQueue.maxSize
}
return {
tasks: {
return worker.id
}
}
-
- /**
- * Executes a function once at a time.
- *
- * @param fn - The function to execute.
- * @param context - The context to bind the function to.
- * @returns The function to execute.
- */
- 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
- }
- }
- }
}