1
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.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • Why should it? If you expect execution in a specific sequence, you should write sequential code. Otherwise don't hold unwarranted assumptions. – Kerrek SB Oct 27 '16 at 16:22
  • I hope the fiber after creation will be implemented immediately. But doesn't seem to find the appropriate method, fiber.join() method is Is blocked. I hope to find a not blocking and executed immediately – Shen.TongLe Oct 28 '16 at 02:08

1 Answers1

0

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));
xlrg
  • 1,994
  • 1
  • 16
  • 14