Created
August 12, 2024 14:47
-
-
Save satyam4p/4dcba8a4d144bde5f85264c19093b0a1 to your computer and use it in GitHub Desktop.
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
//We will now look at pattern that will execute set of given tasks in parallel with given concurrency. | |
function makeSimpleTask(name) { | |
return (cb) => { | |
console.log("started"); | |
setTimeout(() => { | |
console.log(name, "completed"); | |
cb(); | |
}, Math.random() * 2000); | |
}; | |
} | |
const tasks = [ | |
makeSimpleTask("task 1"), | |
makeSimpleTask("task 2"), | |
makeSimpleTask("task 3"), | |
makeSimpleTask("task 4"), | |
makeSimpleTask("task 5"), | |
makeSimpleTask("task 6"), | |
makeSimpleTask("task 7"), | |
]; | |
const concurrency = 2; | |
let running = 0; | |
let index = 0; | |
let completed = 0; | |
function next() { | |
while (running < concurrency && index < tasks.length) { | |
const task = tasks[index++]; | |
task(() => { | |
if (++completed == tasks.length) { | |
return finish(); | |
} | |
running--; | |
next(); | |
}); | |
running++; | |
} | |
} | |
next(); | |
function finish() { | |
console.log("all tasks completed"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment