Skip to content

Instantly share code, notes, and snippets.

@b2whats
Forked from narqo/producer-consumer.js
Created April 13, 2016 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b2whats/d0cef9ab2616c9a4c361ef49542b8517 to your computer and use it in GitHub Desktop.
Save b2whats/d0cef9ab2616c9a4c361ef49542b8517 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