简体   繁体   中英

Unexpected output with boost coroutine2

This is the test case

#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);
}

For some reason the assert at the end fails with the value of sum being 14 I installed boost (version 1.63) context with the command

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

I am running this on a MacOS 10.12.6 . The compile command was

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

Where boost is the boost folder downloaded from sourceforge.

The output of the above test case strangely without the assert is this

Transferring 1
Currently 0
Transferring 2
Currently 2
Currently 2

Why is the first line printed in the coroutine Currently 0 ? Also why is Currently 2 is printed twice here?? The latter can be seen here as well https://wandbox.org/permlink/zEL9fGT5MrzWGgQB


For the second question it seems like after the main thread has finished, control is transferred back to the coroutine one last time. Why is that? That seems strange..

UPDATE : For the second question, it seems to be different in boost 1.65??!? https://wandbox.org/permlink/JQa9Wq1jp8kB49Up

output of your app with boost-1.65.1 is:

Transferring 1
Currently 1
Transferring 2
Currently 2

probably your problem was caused by bug that has been fixed in boost-1.63

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM