Created
January 21, 2016 06:16
-
-
Save DuaneNielsen/99bd2540da070fbda061 to your computer and use it in GitHub Desktop.
Javascript Barrier Sync with a limited number of threads
This file contains hidden or 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 async(arg, callback) { | |
| console.log('do something with \''+arg+'\', return 1 sec later'); | |
| setTimeout(function() { callback(arg * 2); }, 1000); | |
| } | |
| function final() { console.log('Done', results); } | |
| var items = [ 1, 2, 3, 4, 5, 6 ]; | |
| var results = []; | |
| var running = 0; | |
| var limit = 2; | |
| function launcher() { | |
| while(running < limit && items.length > 0) { | |
| var item = items.shift(); | |
| async(item, function(result) { | |
| results.push(result); | |
| running--; | |
| if(items.length > 0) { | |
| launcher(); | |
| } else if(running == 0) { | |
| final(); | |
| } | |
| }); | |
| running++; | |
| } | |
| } | |
| launcher(); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://book.mixu.net/node/ch7.html