Skip to content

Instantly share code, notes, and snippets.

@narqo
Created December 29, 2013 19:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save narqo/8173984 to your computer and use it in GitHub Desktop.
Save narqo/8173984 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
/* 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