Created
May 15, 2012 13:01
-
-
Save cho45/2701583 to your computer and use it in GitHub Desktop.
This file contains 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
var cluster = require('cluster'); | |
var fs = require('fs'); | |
if (!cluster.isMaster) { | |
process.on('message', function (e) { | |
e.args.unshift(function (result) { | |
fs.writeFileSync(e.path + '~', JSON.stringify({ result : result })); | |
fs.renameSync(e.path + '~', e.path); | |
process.exit(); | |
}); | |
eval('(' + e.process + ')').apply(this, e.args); | |
}); | |
return; | |
} | |
function future (process) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
var temp = '/tmp/' + Math.random().toString(16); | |
var worker = cluster.fork(); | |
var result; | |
worker.send({ process: process.toString(), args: args, path : temp }); | |
var ret = { | |
resolved : false, | |
result : undefined, | |
valueOf : function () { | |
if (!this.resolved) { | |
while (1) { | |
try { | |
result = fs.readFileSync(temp); | |
fs.unlinkSync(temp); | |
break; | |
} catch (e) { } | |
} | |
this.resolved = true; | |
this.result = JSON.parse(result).result; | |
} | |
return this.result; | |
} | |
}; | |
return ret; | |
} | |
var foo = future(function (cb) { setTimeout(function () { cb(2) }, 2000) }); | |
var bar = future(function (cb) { setTimeout(function () { cb(3) }, 3000) }); | |
console.log(new Date() + ''); | |
// block | |
console.log([foo + bar]); | |
console.log(new Date() + ' / 3 second (not 6 second) blocked?'); | |
// non-block | |
console.log([foo + bar]); | |
console.log(new Date()); | |
console.log('non blocked?'); | |
console.log('sleep // this is just busy loop :)'); | |
function sleep (n) { future(function (cb, n) { console.log(n); setTimeout(cb, n) }, n).valueOf() } | |
sleep(1000); | |
console.log('done!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment