Last active
December 24, 2019 07:38
-
-
Save RubaXa/baf645d76785b2962f0c93297cb72a82 to your computer and use it in GitHub Desktop.
Worker Pool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createWorkerPool< | |
A extends object, | |
E extends object, | |
R extends any, | |
>(size: number, init: () => E, worker: (args: A, env: E) => Promise<R>) { | |
const pool = [] as Array<{ | |
args: A; | |
resolve: (promise: Promise<R>) => void | |
}>; | |
const units = [] as Array<{ | |
env: E, | |
idle: boolean; | |
}>; | |
function tick() { | |
if (pool.length) { | |
let unit = units.find(u => u.idle); | |
if (units.length < size && !unit) { | |
unit = { | |
env: init(), | |
idle: true, | |
}; | |
units.push(unit); | |
} | |
if (unit) { | |
const task = pool.shift(); | |
if (!task) { | |
return; | |
} | |
unit.idle = false; | |
const promise = Promise.resolve(worker(task.args, unit.env)); | |
task.resolve(promise); | |
promise.then(finish(unit), finish(unit)) | |
} | |
} | |
} | |
function finish(unit) { | |
return () => { | |
unit.idle = true; | |
tick(); | |
}; | |
} | |
return (args: A) => new Promise<R>((resolve) => { | |
pool.push({ | |
args, | |
resolve, | |
}); | |
tick(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example