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
, task
, opts
) {
22 throw new Error('Cannot start a thread pool from a worker thread !!!')
24 this.numThreads
= numThreads
27 for (let i
= 1; i
<= numThreads
; i
++) {
28 const worker
= new Worker(__filename
)
29 this.workers
.push(worker
)
30 const { port1
} = new MessageChannel()
31 worker
.emitter
= port1
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 idx
= chooseWorker(0, this.numThreads
- 1)
44 const worker
= this.workers
[idx
]
45 const id
= generateID()
46 const res
= this._execute(worker
, task
, id
)
47 worker
.emitter
.emit(id
, data
)
51 _execute (worker
, task
, id
) {
52 return new Promise((resolve
, reject
) => {
53 console
.log('Executing a task on worker thread ' + worker
.threadId
)
54 worker
.emitter
.once(id
, (data
) => {
55 console
.log('Receivd a message')
66 function chooseWorker (min
, max
) {
69 return Math
.floor(Math
.random() * (max
- min
+ 1)) + min
73 * Return an id to be associated to a node.
75 const generateID
= () => {
81 module
.exports
= FixedThreadPool