-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker-pool.js
71 lines (62 loc) · 2.09 KB
/
worker-pool.js
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
'use strict'
/***
* This Worker Pool is from:
* https://blog.insiderattack.net/deep-dive-into-worker-threads-in-node-js-e75e10546b11
*/
const {Worker, MessageChannel, parentPort} = require('worker_threads')
const os = require('os')
const WORKER_STATUS = {
IDLE: 'idle',
BUSY: 'busy'
}
module.exports.WorkerPool = class WorkerPool {
constructor(script, size = os.cpus().length) {
this.script = script
this.size = size // defaults to number of CPUs machine has
this.pool = []
this.initialize()
}
initialize() {
for (let i = 0; i < this.size; i++) {
const worker = new Worker(this.script)
this.pool.push({status: WORKER_STATUS.IDLE, worker})
worker.once('exit', () => {
worker.emit(`worker ${worker.threadId} terminated`)
})
}
}
getIdleWorker() {
const idleWorker = this.pool.find(w => w.status === WORKER_STATUS.IDLE)
if (idleWorker) return idleWorker.worker
// If no idle worker found, return random worker.
return this.pool[Math.ceil(Math.random() * this.size)].worker
}
setWorkerIdle(worker) {
const currWorker = this.pool.find(w => w.worker === worker)
if (currWorker) currWorker.status = WORKER_STATUS.IDLE
}
setWorkerBusy(worker) {
const currWorker = this.pool.find(w => w.worker === worker)
if (currWorker) currWorker.status = WORKER_STATUS.BUSY
}
sendWork(data, callback) {
const worker = this.getIdleWorker()
this.setWorkerBusy(worker)
const {port1, port2} = new MessageChannel()
worker.postMessage({data, port: port1}, [port1])
port2.once('message', (result) => {
this.setWorkerIdle(worker)
callback(null, result)
})
port2.once('error', (err) => {
this.setWorkerIdle(worker)
callback(err)
})
}
}
module.exports.wrapAsWorker = (workerFunc) => {
parentPort.on('message', ({data, port}) => {
const result = workerFunc(data)
port.postMessage(result)
})
}