1

ブースト 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

出力は、最初の 2 つのリンクとは異なります。バグですか?

4

1 に答える 1

3

あなたの答えは、ドキュメントの最初の文にあります。

構築時に実行制御をコルーチンに移す(コルーチン関数入り)

コルーチンを構築すると、ほとんどすぐに呼び出されるため、最初の行が message の前に出力されますmain() starts coroutine c。コルーチンは実際にはここから始まります。

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

例自体と比較して、出力例は正しくないと主張します。std::cout実際、 の 2 つの呼び出しの間にはmain以外のコードがないため、出力が例とどのように一致while (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 に答える