forked from waldemarnt/node-docker-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacciWorkerPool.js
More file actions
32 lines (29 loc) · 980 Bytes
/
fibonacciWorkerPool.js
File metadata and controls
32 lines (29 loc) · 980 Bytes
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
const fb = require('fibonacci');
const { isMainThread, parentPort, workerData } = require('worker_threads');
const Pool = require('worker-threads-pool');
const CPUs = require('os').cpus().length;
const pool = new Pool({ max: CPUs });
const runFibonacci = workerData => {
return new Promise((resolve, reject) => {
pool.acquire(__filename, { workerData }, (err, worker) => {
if (err) reject(err);
console.log(`started worker ${worker} (pool size: ${pool.size})`);
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', code => {
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
});
});
});
};
/**
* If it's not the main thread it's one of the Worker threads
*/
if (!isMainThread) {
const result = fb.iterate(workerData.iterations);
/**
* Send a copy the result object back to the main Thread
*/
parentPort.postMessage(result);
}
module.exports = runFibonacci;