-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
fixed.ts
104 lines (93 loc) · 2.46 KB
/
fixed.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import {
SHARE_ENV,
Worker,
type WorkerOptions,
isMainThread
} from 'node:worker_threads'
import type { MessageValue } from '../../utility-types'
import { AbstractPool } from '../abstract-pool'
import {
type PoolOptions,
type PoolType,
PoolTypes,
type WorkerType,
WorkerTypes
} from '../pool'
/**
* Options for a poolifier thread pool.
*/
export interface ThreadPoolOptions extends PoolOptions<Worker> {
/**
* Worker options.
*
* @see https://nodejs.org/api/worker_threads.html#new-workerfilename-options
*/
workerOptions?: WorkerOptions
}
/**
* A thread pool with a fixed number of threads.
*
* @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
* @typeParam Response - Type of execution response. This can only be structured-cloneable data.
* @author [Alessandro Pio Ardizio](https://github.com/pioardi)
* @since 0.0.1
*/
export class FixedThreadPool<
Data = unknown,
Response = unknown
> extends AbstractPool<Worker, Data, Response> {
/**
* Constructs a new poolifier fixed thread pool.
*
* @param numberOfThreads - Number of threads for this pool.
* @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
* @param opts - Options for this fixed thread pool.
*/
public constructor (
numberOfThreads: number,
filePath: string,
protected readonly opts: ThreadPoolOptions = {}
) {
super(numberOfThreads, filePath, opts)
}
/** @inheritDoc */
protected isMain (): boolean {
return isMainThread
}
/** @inheritDoc */
protected async destroyWorker (worker: Worker): Promise<void> {
this.sendToWorker(worker, { kill: 1 })
await worker.terminate()
}
/** @inheritDoc */
protected sendToWorker (worker: Worker, message: MessageValue<Data>): void {
worker.postMessage(message)
}
/** @inheritDoc */
protected createWorker (): Worker {
return new Worker(this.filePath, {
env: SHARE_ENV,
...this.opts.workerOptions
})
}
/** @inheritDoc */
protected get type (): PoolType {
return PoolTypes.fixed
}
/** @inheritDoc */
protected get worker (): WorkerType {
return WorkerTypes.thread
}
/** @inheritDoc */
protected get minSize (): number {
return this.numberOfWorkers
}
/** @inheritDoc */
protected get maxSize (): number {
return this.numberOfWorkers
}
/** @inheritDoc */
protected get busy (): boolean {
return this.internalBusy()
}
}