Thread pools are built on top of Node.js [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads) module.
**Cluster pools** (FixedClusterPool and DynamicClusterPool) are suggested to run I/O intensive tasks, again you can still run CPU intensive tasks into cluster pools, but performance enhancement is expected to be minimal.
-Cluster pools are built on top of Node.js [cluster](https://nodejs.org/api/cluster.html) module.
+Cluster pools are built on top of Node.js [cluster](https://nodejs.org/api/cluster.html) module.
**Remember** that some Node.js tasks are execute by Node.js into the libuv worker pool at process level as explained [here](https://nodejs.org/en/docs/guides/dont-block-the-event-loop/#what-code-runs-on-the-worker-pool).
// Threads.js is not really a pool so we need to write few additional code
const workers = []
async function poolify () {
- for (let i = 0; i < size ; i++ ){
- const worker = await spawn(new Worker("./workers/threadjs/function-to-bench-worker.js"))
+ for (let i = 0; i < size; i++) {
+ const worker = await spawn(
+ new Worker('./workers/threadjs/function-to-bench-worker.js')
+ )
workers.push(worker)
}
}
-
async function run () {
await poolify()
const promises = []
for (let i = 0; i < iterations; i++) {
- const worker = workers[(i % size)]
+ const worker = workers[i % size]
promises.push(worker.exposedFunction(data))
}
await Promise.all(promises)
'use strict'
-const { expose } = require("threads/worker")
+const { expose } = require('threads/worker')
const functionToBench = require('../../functions/function-to-bench')
expose({
MessageValue,
PromiseWorkerResponseWrapper
} from '../utility-types'
+import { isKillBehavior, KillBehaviors } from '../worker/worker-options'
import type { IPoolInternal } from './pool-internal'
import { PoolEmitter } from './pool-internal'
import type { WorkerChoiceStrategy } from './selection-strategies'
Data = unknown,
Response = unknown
> implements IPoolInternal<Worker, Data, Response> {
+ /** @inheritdoc */
+ public readonly workers: Worker[] = []
+
+ /** @inheritdoc */
+ public readonly tasks: Map<Worker, number> = new Map<Worker, number>()
+
+ /** @inheritdoc */
+ public readonly emitter: PoolEmitter
+
/**
* The promise map.
*
PromiseWorkerResponseWrapper<Worker, Response>
> = new Map<number, PromiseWorkerResponseWrapper<Worker, Response>>()
- /** @inheritdoc */
- public readonly workers: Worker[] = []
-
- /** @inheritdoc */
- public readonly tasks: Map<Worker, number> = new Map<Worker, number>()
-
- /** @inheritdoc */
- public readonly emitter: PoolEmitter
-
/**
* ID of the next message.
*/
this.emitter = new PoolEmitter()
this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
this,
+ () => {
+ const workerCreated = this.createAndSetupWorker()
+ this.registerWorkerMessageListener(workerCreated, message => {
+ const tasksInProgress = this.tasks.get(workerCreated)
+ if (
+ isKillBehavior(KillBehaviors.HARD, message.kill) ||
+ tasksInProgress === 0
+ ) {
+ // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
+ void this.destroyWorker(workerCreated)
+ }
+ })
+ return workerCreated
+ },
opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
)
}
await Promise.all(this.workers.map(worker => this.destroyWorker(worker)))
}
- /** @inheritdoc */
- public abstract destroyWorker (worker: Worker): void | Promise<void>
+ /**
+ * Shut down given worker.
+ *
+ * @param worker A worker within `workers`.
+ */
+ protected abstract destroyWorker (worker: Worker): void | Promise<void>
/**
* Setup hook that can be overridden by a Poolifier pool implementation
message: MessageValue<Data>
): void
- /** @inheritdoc */
- public abstract registerWorkerMessageListener<
+ /**
+ * Register a listener callback on a given worker.
+ *
+ * @param worker A worker.
+ * @param listener A message listener callback.
+ */
+ protected abstract registerWorkerMessageListener<
Message extends Data | Response
> (worker: Worker, listener: (message: MessageValue<Message>) => void): void
*/
protected abstract afterWorkerSetup (worker: Worker): void
- /** @inheritdoc */
- public createAndSetupWorker (): Worker {
+ /**
+ * Creates a new worker for this pool and sets it up completely.
+ *
+ * @returns New, completely set up worker.
+ */
+ protected createAndSetupWorker (): Worker {
const worker: Worker = this.createWorker()
worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
* @returns The listener function to execute when a message is sent from a worker.
*/
protected workerListener (): (message: MessageValue<Response>) => void {
- const listener: (message: MessageValue<Response>) => void = message => {
+ return message => {
if (message.id) {
const value = this.promiseMap.get(message.id)
if (value) {
}
}
}
- return listener
}
}
import EventEmitter from 'events'
-import type { MessageValue } from '../utility-types'
import type { IWorker } from './abstract-pool'
import type { IPool } from './pool'
* Maximum number of workers that can be created by this pool.
*/
readonly max?: number
-
- /**
- * Creates a new worker for this pool and sets it up completely.
- *
- * @returns New, completely set up worker.
- */
- createAndSetupWorker(): Worker
-
- /**
- * Shut down given worker.
- *
- * @param worker A worker within `workers`.
- */
- destroyWorker(worker: Worker): void | Promise<void>
-
- /**
- * Register a listener callback on a given worker.
- *
- * @param worker A worker.
- * @param listener A message listener callback.
- */
- registerWorkerMessageListener<Message extends Data | Response>(
- worker: Worker,
- listener: (message: MessageValue<Message>) => void
- ): void
}
-import { isKillBehavior, KillBehaviors } from '../worker/worker-options'
import type { IWorker } from './abstract-pool'
import type { IPoolInternal } from './pool-internal'
* Constructs a worker choice strategy for dynamical pools.
*
* @param pool The pool instance.
+ * @param createDynamicallyWorkerCallback The worker creation callback for dynamic pool.
* @param workerChoiceStrategy The worker choice strategy when the pull is full.
*/
public constructor (
private readonly pool: IPoolInternal<Worker, Data, Response>,
+ private createDynamicallyWorkerCallback: () => Worker,
workerChoiceStrategy: WorkerChoiceStrategy = WorkerChoiceStrategies.ROUND_ROBIN
) {
this.workerChoiceStrategy = SelectionStrategiesUtils.getWorkerChoiceStrategy(
/** @inheritdoc */
public choose (): Worker {
const freeWorker = SelectionStrategiesUtils.findFreeWorkerBasedOnTasks(
- this.pool
+ this.pool.tasks
)
if (freeWorker) {
return freeWorker
}
// All workers are busy, create a new worker
- const workerCreated = this.pool.createAndSetupWorker()
- this.pool.registerWorkerMessageListener(workerCreated, message => {
- const tasksInProgress = this.pool.tasks.get(workerCreated)
- if (
- isKillBehavior(KillBehaviors.HARD, message.kill) ||
- tasksInProgress === 0
- ) {
- // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
- void this.pool.destroyWorker(workerCreated)
- }
- })
- return workerCreated
+ return this.createDynamicallyWorkerCallback()
}
}
* Worker choice strategy context constructor.
*
* @param pool The pool instance.
+ * @param createDynamicallyWorkerCallback The worker creation callback for dynamic pool.
* @param workerChoiceStrategy The worker choice strategy.
*/
public constructor (
private readonly pool: IPoolInternal<Worker, Data, Response>,
+ private createDynamicallyWorkerCallback: () => Worker,
workerChoiceStrategy: WorkerChoiceStrategy = WorkerChoiceStrategies.ROUND_ROBIN
) {
this.setWorkerChoiceStrategy(workerChoiceStrategy)
if (this.pool.dynamic) {
return new DynamicPoolWorkerChoiceStrategy(
this.pool,
+ this.createDynamicallyWorkerCallback,
workerChoiceStrategy
)
}
*
* If no free worker was found, `null` will be returned.
*
- * @param pool The pool instance.
+ * @param workerTasksMap The pool worker tasks map.
* @returns A free worker if there was one, otherwise `null`.
*/
- public static findFreeWorkerBasedOnTasks<
- Worker extends IWorker,
- Data,
- Response
- > (pool: IPoolInternal<Worker, Data, Response>): Worker | null {
- for (const [worker, numberOfTasks] of pool.tasks) {
+ public static findFreeWorkerBasedOnTasks<Worker extends IWorker> (
+ workerTasksMap: Map<Worker, number>
+ ): Worker | null {
+ for (const [worker, numberOfTasks] of workerTasksMap) {
if (numberOfTasks === 0) {
// A worker is free, use it
return worker