c++boostfiber

when execute after fiber.detach()?


void helloFiber(boost::fibers::future<void> &f)
{
    cout << "Hello, boost::fiber" << endl;
    f.get();
}

int main()
{
    boost::fibers::promise<void> pm;
    boost::fibers::future<void> ft = pm.get_future();
    {
        boost::fibers::fiber f(helloFiber, std::move(ft));
        cout << "Before join." << endl;
        f.detach();
    }
    pm.set_value();
    cout << "After join." << endl;
    return 0;
}

This program outputs: Before join. After join. Hello, boost::fiber.

Why does it not output: Before join. Hello, boost::fiber After join.


Solution

  • You should change the signature of helloFiber() to an rvalue reference to future (you move the future).

    Because you detach the fiber, the scheduler has to join it (in your example at destruction).

    Please take a look at: http://www.boost.org/doc/libs/1_62_0/libs/fiber/doc/html/fiber/fiber_mgmt.html (section: Enumeration launch):

    'enumeration launch specifies whether control passes immediately into a newly-launched fiber.'

    boost::fibers::fiber f( boost::fibers::launch::post, helloFiber, std::move(ft));
    boost::fibers::fiber f( boost::fibers::launch::dispatch, helloFiber, std::move(ft));
    

    The deafult is post - but you want dispatch, so the output is:

    Hello, boost::fiber Before join. After join.

    It will never print: 'Before join. Hello, boost::fiber After join.' because you put

    cout << "Before join." << endl;
    

    after

       boost::fibers::fiber f(helloFiber, std::move(ft));