3 Worker
, isMainThread
, MessageChannel
4 } = require('worker_threads')
6 // FixedThreadPool , TrampolineThreadPool
8 * A thread pool with a static number of threads , is possible to execute tasks in sync or async mode as you prefer
9 * @author Alessandro Pio Ardizio
12 class FixedThreadPool
{
15 * @param {Number} numThreads Num of threads for this worker pool
16 * @param {Object} an object with possible options for example maxConcurrency
18 constructor (numThreads
, task
, opts
) {
20 throw new Error('Cannot start a thread pool from a worker thread !!!')
22 this.numThreads
= numThreads
26 for (let i
= 1; i
<= numThreads
; i
++) {
27 const worker
= new Worker(__filename
)
28 this.workers
.push(worker
)
29 const { port1
} = new MessageChannel()
30 worker
.emitter
= port1
36 * @param {Function} task , a function to execute
37 * @param {Any} the input for the task specified
39 execute (task
, data
) {
40 // TODO select a worker
41 // configure worker to handle message with the specified task
42 const worker
= this._chooseWorker()
43 const id
= generateID()
44 const res
= this._execute(worker
, task
, id
)
45 worker
.emitter
.emit(id
, data
)
49 _execute (worker
, task
, id
) {
50 return new Promise((resolve
, reject
) => {
51 console
.log('Executing a task on worker thread ' + worker
.threadId
)
52 worker
.emitter
.once(id
, (data
) => {
53 console
.log('Receivd a message')
64 console
.log(this.workers
.length
-1)
65 console
.log(this.nextWorker
)
66 if ((this.workers
.length
- 1) === this.nextWorker
) {
67 console
.log('we are here')
69 return this.workers
[this.nextWorker
]
72 return this.workers
[this.nextWorker
]
78 * Return an id to be associated to a node.
80 const generateID
= () => {
86 module
.exports
= FixedThreadPool