- if (worker) {
- // a worker is free, use it
- return worker
- } else {
- if (this.workers.length === this.max) {
- this.emitter.emit('FullPool')
- return super.chooseWorker()
- }
- // all workers are busy create a new worker
- const worker = this.internalNewWorker()
- worker.on('message', (message: MessageValue<Data>) => {
- if (message.kill) {
- this.sendToWorker(worker, { kill: 1 })
- void this.destroyWorker(worker)
- // clean workers from data structures
- const workerIndex = this.workers.indexOf(worker)
- this.workers.splice(workerIndex, 1)
- this.tasks.delete(worker)
- }
- })
- return worker
- }