3 Worker
, isMainThread
, MessageChannel
4 } = require('worker_threads')
6 console
.log('Fixed required')
8 // FixedThreadPool , TrampolineThreadPool
10 * A thread pool with a static number of threads , is possible to execute tasks in sync or async mode as you prefer
11 * @author Alessandro Pio Ardizio
14 class FixedThreadPool
{
17 * @param {Number} numThreads Num of threads for this worker pool
18 * @param {Object} an object with possible options for example maxConcurrency
20 constructor (numThreads
, opts
) {
22 throw new Error('Cannot start a thread pool from a worker thread !!!')
24 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
, port2
} = new MessageChannel()
30 worker
.receiverPort
= port1
31 worker
.sendPort
= port2
37 * @param {Function} task , a function to execute
38 * @param {Any} the input for the task specified
40 execute (task
, data
) {
41 // TODO select a worker
42 // configure worker to handle message with the specified task
43 const res
= this._execute(this.workers
[0], task
)
44 this.workers
[0].sendPort
.postMessage(data
)
48 _execute (worker
, task
) {
49 return new Promise((resolve
, reject
) => {
50 worker
.receiverPort
.on('message', (data
) => {
61 module
.exports
= FixedThreadPool