Skip to content

Instantly share code, notes, and snippets.

@wwiechorek
Last active July 19, 2022 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwiechorek/ebc6b781e85681e6b1bc522df458a1dc to your computer and use it in GitHub Desktop.
Save wwiechorek/ebc6b781e85681e6b1bc522df458a1dc to your computer and use it in GitHub Desktop.
Simple worker pool in javascript/nodejs
function createWorkerPool(max) {
let current = 0
let queue = []
async function run() {
if(current >= max || queue.length === 0) return
current++
let action = queue.shift()
new Promise(async resolve => {
await action()
current--
run()
})
}
return ({
add: (action) => {
queue.push(action)
run()
}
})
}
//Usage exemple ::::
const worker = createWorkerPool(2)
worker.add(async function() {
//terceira execução
await new Promise(resolve => setTimeout(() => resolve(), 2000))
console.log("Primeira ação")
})
worker.add(async function() {
//primeira execução porque executa 1 segundo mais rápido
await new Promise(resolve => setTimeout(() => resolve(), 1000))
console.log("Segunda ação")
})
worker.add(function() {
//segunda execução porque executa depois da primeira que libeira uma posição no workerpool
console.log("Terceira ação")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment