-
-
Save xgrommx/1c95b57a8ba2cd0d31a4 to your computer and use it in GitHub Desktop.
"Producer-Consumer" example implementation using generators. See http://en.wikipedia.org/wiki/Deterministic_concurrency#Comparison_with_generators for more about coroutine
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
/* jshint esnext:true */ | |
/** | |
* "Producer-Consumer" implementation using generators. | |
* @see http://en.wikipedia.org/wiki/Deterministic_concurrency#Comparison_with_generators | |
*/ | |
var SIZE = 3, | |
queue = newQueue(); | |
function *produce() { | |
while(true) { | |
log('going to produce items'); | |
var item, i; | |
for(i = 0; i < SIZE; i++) { | |
log('producing item', i); | |
item = 'item' + i; | |
queue[i] = item; | |
} | |
log(i, 'items produced'); | |
yield consume; | |
} | |
} | |
function *consume() { | |
while(true) { | |
log('going to consume items'); | |
var item, i; | |
for(i = 0; i < SIZE; i++) { | |
log('remove item', i, 'from queue'); | |
item = queue[i]; | |
} | |
flush(); | |
yield produce; | |
} | |
} | |
function dispatcher(n) { | |
(n > 0) || (n = 1); | |
var map = new WeakMap(); | |
map.set(consume, consume()); | |
map.set(produce, produce()); | |
var current = produce, | |
i = 0; | |
do { | |
current = map.get(current).next().value; | |
} while(++i < n*2); | |
} | |
function log() { | |
console.log.apply(console, arguments); | |
} | |
function newQueue() { | |
return new Array(SIZE); | |
} | |
function flush() { | |
var data = queue; | |
queue = newQueue(); | |
return data; | |
} | |
dispatcher(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment