From 2cde41bb5f46faf917eacd330d709b07db70cd93 Mon Sep 17 00:00:00 2001 From: Vitaliy Filippov Date: Mon, 27 Jun 2016 16:03:06 +0300 Subject: [PATCH] Initial commit --- example.js | 24 ++++++++++++++++++++++++ index.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 example.js create mode 100644 index.js diff --git a/example.js b/example.js new file mode 100644 index 0000000..022011a --- /dev/null +++ b/example.js @@ -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); }); diff --git a/index.js b/index.js new file mode 100644 index 0000000..375006d --- /dev/null +++ b/index.js @@ -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); })); +}