c++ - boost 协程 2 的意外输出

标签 c++ c++11 boost c++14 boost-coroutine

这是测试用例

#include <boost/coroutine2/all.hpp>

#include <iostream>
#include <cassert>

int main() {
    auto sum = 0;
    using Coroutine_t = boost::coroutines2::coroutine<int>::push_type;
    auto coro = Coroutine_t{[&](auto& yield) {
        for (;;) {
            auto val = yield.get();
            std::cout << "Currently " << val << std::endl;
            sum += val;
            yield(); // jump back to starting context
         }
    }};

    std::cout << "Transferring 1" << std::endl;
    coro(1); // transfer {1} to coroutine-function
    std::cout << "Transferring 2" << std::endl;
    coro(2); // transfer {1} to coroutine-function

    // assert(sum == 3);
}

由于某种原因,最后的断言失败,总和的值为 14 我使用命令安装了 boost(版本 1.63)上下文

./bootstrap.sh --prefix=build --with-libraries=context
./b2 --prefix=build --with-context

我在 MacOS 10.12.6 上运行它。编译命令是

g++ -std=c++14 -O3 -I boost co.cpp boost/stage/lib/libboost_*.a

其中boost是从sourceforge下载的boost文件夹。

奇怪的是,没有assert的上述测试用例的输出是这样的

Transferring 1
Currently 0
Transferring 2
Currently 2
Currently 2

为什么协程中打印的第一行是Currently 0?还有为什么 Currently 2 在这里打印两次?后者也可以在这里看到 https://wandbox.org/permlink/zEL9fGT5MrzWGgQB


对于第二个问题,似乎是在主线程完成后,最后一次将控制权转移回协程。这是为什么?这看起来很奇怪..

更新:对于第二个问题,boost 1.65 似乎有所不同??!? https://wandbox.org/permlink/JQa9Wq1jp8kB49Up

最佳答案

使用 boost-1.65.1 的应用输出为:

Transferring 1
Currently 1
Transferring 2
Currently 2

可能你的问题是由 boost-1.63 中已修复的错误引起的

关于c++ - boost 协程 2 的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46265373/

相关文章:

c++ - 类中的枚举是静态的吗?

c++ - 使用特定范围内的随机数初始化特征矩阵或 vector 的有效方法?

c++ - C++ 中 "using"关键字背后的逻辑是什么?

c++ - 如何专门化模板类中的赋值运算符?

c++ - 服务器关闭时客户端上的 boost asio 写入操作被阻止

c++ - VC++ 中的文字类型

c++ - 如何用适当的容器表示冲突?

STL 容器中的 C++11 shared_pointer constness

c++ - 使用条件变量的生产者和消费者线程

c++ - 侵入式_ptr : Why isn't a common base class provided?