Initial commit
commit
2cde41bb5f
|
@ -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); });
|
|
@ -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); }));
|
||||
}
|
Loading…
Reference in New Issue