gpt4 book ai didi

c++ - boost1.53协程的bug?

转载 作者:行者123 更新时间:2023-11-30 02:51:09 25 4
gpt4 key购买 nike

我使用 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

输出与前两个中的链接不同。是Bug吗?

最佳答案

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

The execution control is transferred to coroutine at construction (coroutine-function entered)

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

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

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

    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

关于c++ - boost1.53协程的bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19908260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com