如何阻止主线,直到一根或多根纤维完成?

时间:2014-04-22 15:29:41

标签: node.js node-fibers

我使用fibersnode.js。假设我创建了几个光纤,并希望在主线程中等待它们中的任何一个完成。 Fiber对象的API仅列出非阻塞函数,例如runFuture对象似乎根本没有记录。那应该怎么做呢?这是一个示例程序(缺少waitForSomeFiberToFinish函数的定义):

var Fiber = require('fibers');

function sleep(ms) {
  var fiber = Fiber.current;
  setTimeout(function() {
    fiber.run();
  }, ms);
  Fiber.yield();
}

f1 = Fiber(function(){sleep(1000);});
f2 = Fiber(function(){sleep(2000);});

f1.run();
f2.run();

// The question is: how does one implement waitForSomeFiberToFinish?
waitForSomeFiberToFinish([f1, f2]);
console.log('We should have slept now for one second and at this point f1 is finished');
waitForSomeFiberToFinish([f1, f2]);
console.log('We should have slept now for another second and at this point f2 is finished');

0 个答案:

没有答案