1

我使用 boost 1.53 的协程并尝试来自http://www.boost.org/doc/libs/1_53_0/libs/coroutine/doc/html/coroutine/coroutine.html#coroutine.coroutine.calling_a_coroutine的代码:

typedef boost::coroutines::coroutine< void() > coro_t;
void fn( coro_t::caller_type & ca, int j) {
  for(int i = 0; i < j; ++i) {
    std::cout << "fn(): local variable i == " << i << std::endl;
    ca();
  }
}

int main(int argc, char *argv[]) {
  // bind parameter '7' to coroutine-fn
  coro_t c( boost::bind( fn, _1, 7) );

  std::cout << "main() starts coroutine c" << std::endl;

  while ( c)
  {
    std::cout << "main() calls coroutine c" << std::endl;
    // execution control is transferred to c
    c();
  }

  std::cout << "Done" << std::endl;

  return EXIT_SUCCESS;
}

输出:

fn(): local variable i == 0
main() starts coroutine c
main() calls coroutine c
fn(): local variable i == 1
main() calls coroutine c
fn(): local variable i == 2
main() calls coroutine c
fn(): local variable i == 3
main() calls coroutine c
fn(): local variable i == 4
main() calls coroutine c
fn(): local variable i == 5
main() calls coroutine c
fn(): local variable i == 6
main() calls coroutine c
Done

输出与前两个中的链接不同。它是一个错误吗?

4

1 回答 1

3

您的答案在文档的第一句话中:

执行控制在构造时转移到协程(进入协程函数)

当您构建协程时,它会立即调用它,因此第一行会在您的 message 之前打印main() starts coroutine c。协程实际上从这里开始:

    coro_t c( boost::bind( fn, _1, 7) );

我认为他们的示例输出与示例本身相比是不正确的。事实上,除了之外的两个std::cout调用之间没有代码,所以我看不出输出如何与示例匹配。我不认为测试延续谓词应该启动协程。鉴于第一个之后的例子,我怀疑他们打算写:mainwhile (c)

    std::cout << "main() starts coroutine c" << std::endl;

    // bind parameter '7' to coroutine-fn
    coro_t c( boost::bind( fn, _1, 7) );

您可以在他们的下一个示例中看到,他们在消息之后main调用构造函数并获得您期望的输出:

int main( int argc, char * argv[])
{
    std::cout << "main(): call coroutine c" << std::endl;
    coro_t c( fn, 7);

    int x = c.get();
    std::cout << "main(): transferred value: " << x << std::endl;

    x = c( 10).get();
    std::cout << "main(): transferred value: " << x << std::endl;

    std::cout << "Done" << std::endl;

    return EXIT_SUCCESS;
}

导致:

output:
    main(): call coroutine c
    fn(): local variable i == 7
    main(): transferred value: 7
    fn(): local variable i == 10
    main(): transferred value: 10
    Done
于 2013-11-11T14:25:48.903 回答