Initial commit

master
Vitaliy Filippov 2016-06-27 16:03:06 +03:00
commit 2cde41bb5f
2 changed files with 57 additions and 0 deletions

24
example.js Normal file
View File

@ -0,0 +1,24 @@
var gen = require('./gen-thread.js');
function* test(thread)
{
console.log('start');
console.log([ 'next', yield setTimeout(function() { thread('zhopa', 123); }, 500) ]);
var args = yield gen.runParallel([
function*(thread)
{
yield setTimeout(function() { thread('callback 1'); }, 500);
return 'result 1';
},
function*(thread)
{
yield setTimeout(function() { thread('callback 2'); }, 500);
return 'result 2';
}
], thread);
console.log('abc');
console.log(args);
return 'result';
}
gen.run(test, null, function(result) { console.log(result); });

33
index.js Normal file
View File

@ -0,0 +1,33 @@
module.exports.run = runThread;
module.exports.runParallel = runParallel;
function runThread(main, arg, done)
{
var thread = function()
{
// pass parameters as yield result
var pass = Array.prototype.slice.call(arguments, 0);
var v = thread.gen.next(pass);
if (v.done && done)
done(v.value);
};
thread.gen = main(thread, arg);
thread();
}
function runParallel(threads, done)
{
var results = [];
var resultCount = 0;
var allDone = function(i, result)
{
if (!results[i])
{
results[i] = result;
resultCount++;
if (resultCount == threads.length)
done(results);
}
};
threads.map((t, i) => runThread(t, null, function(result) { allDone(i, result); }));
}