First commit with a working example of fixed thread pool
[poolifier.git] / fixed.js
1 'use strict'
2 const {
3 Worker, isMainThread, MessageChannel
4 } = require('worker_threads')
5
6 console.log('Fixed required')
7
8 // FixedThreadPool , TrampolineThreadPool
9 /**
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
12 * @since 0.0.1
13 */
14 class FixedThreadPool {
15 /**
16 *
17 * @param {Number} numThreads Num of threads for this worker pool
18 * @param {Object} an object with possible options for example maxConcurrency
19 */
20 constructor (numThreads, opts) {
21 if (!isMainThread) {
22 throw new Error('Cannot start a thread pool from a worker thread !!!')
23 }
24 this.numThreads = numThreads
25 this.workers = []
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
32 }
33 }
34
35 /**
36 *
37 * @param {Function} task , a function to execute
38 * @param {Any} the input for the task specified
39 */
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)
45 return res
46 }
47
48 _execute (worker, task) {
49 return new Promise((resolve, reject) => {
50 worker.receiverPort.on('message', (data) => {
51 try {
52 resolve(task(data))
53 } catch (e) {
54 reject(e)
55 }
56 })
57 })
58 }
59 }
60
61 module.exports = FixedThreadPool