Skip to content

Instantly share code, notes, and snippets.

@noomz
Created October 26, 2014 18:41
Show Gist options
  • Save noomz/c6401cdf1fc01d1f7074 to your computer and use it in GitHub Desktop.
Save noomz/c6401cdf1fc01d1f7074 to your computer and use it in GitHub Desktop.
Node.js mimic Go concurrency : Fan In
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
c := fanIn(boring("boring Joe!"), boring("boring Ann!"))
for i := 0; i < 5; i++ {
fmt.Printf("You say: %q\n", <- c)
}
fmt.Println("You're boring; I'm leaving")
}
func boring(msg string) <-chan string {
c := make(chan string)
go func() {
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c
}
func fanIn(input1, input2 <-chan string) <-chan string {
c := make(chan string)
go func() { for { c <- <-input1 } }()
go func() { for { c <- <-input2 } }()
return c
}
/* jshint latedef:false */
'use strict';
var Fiber = require('fibers'),
// helper for channel communication
SimpleBroadcast = (function () {
var sub = {};
return {
publish: function (topic, data) {
data = data || {};
(sub[topic] || []).forEach(function (func) {
setTimeout(function () {
func(data);
}, 0);
});
},
subscribe: function (topic, func) {
sub[topic] = sub[topic] || [];
sub[topic].push(func);
}
};
})(),
// helper to check if loop count reach.
Wait = function Wait(limitLoop, func) {
var loopCount = 0;
return function () {
if (++loopCount > limitLoop) {
func();
}
};
},
// anothor helper, make us sleep better.
sleep = function sleep(ms) {
var fiber = Fiber.current;
setTimeout(function () {
fiber.run();
}, ms);
Fiber.yield();
};
function main() {
var check;
SimpleBroadcast.subscribe('chan', function (msg) {
check();
console.log('You say: "' + msg + '"');
});
boring('boring Joe!');
boring('boring Ann!');
check = new Wait(5, function () {
console.log('You\'re boring; I\'m leaving');
process.exit();
});
}
function boring(msg) {
Fiber(function () {
var i = 0;
for (;;i++) {
SimpleBroadcast.publish('chan', msg + ' ' + i);
sleep(1000 * Math.random());
}
}).run();
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment