这是测试用例
#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