33fdec970c6a9de20aa431f353d71c627bb80e71
[poolifier.git] / examples / javascript / dynamicExample.js
1 'use strict'
2 const {
3 DynamicThreadPool,
4 PoolEvents,
5 availableParallelism
6 } = require('poolifier')
7
8 const pool = new DynamicThreadPool(
9 Math.floor(availableParallelism() / 2),
10 availableParallelism(),
11 './yourWorker.js',
12 {
13 errorHandler: e => console.error(e),
14 onlineHandler: () => console.info('worker is online')
15 }
16 )
17 let poolFull = 0
18 let poolReady = 0
19 let poolBusy = 0
20 pool.emitter.on(PoolEvents.full, () => poolFull++)
21 pool.emitter.on(PoolEvents.ready, () => poolReady++)
22 pool.emitter.on(PoolEvents.busy, () => poolBusy++)
23
24 let resolved = 0
25 const start = performance.now()
26 const iterations = 1000
27 for (let i = 1; i <= iterations; i++) {
28 pool
29 .execute()
30 .then(() => {
31 resolved++
32 if (resolved === iterations) {
33 console.info(`Time taken is ${performance.now() - start}`)
34 console.info(`The pool was full for ${poolFull} times`)
35 console.info(`The pool was ready for ${poolReady} times`)
36 return console.info(`The pool was busy for ${poolBusy} times`)
37 }
38 return null
39 })
40 .catch(err => console.error(err))
41 }