Last active
July 19, 2022 21:17
-
-
Save wwiechorek/ebc6b781e85681e6b1bc522df458a1dc to your computer and use it in GitHub Desktop.
Simple worker pool in javascript/nodejs
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(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