Victor L
Victor L

Reputation: 10230

How to make a re-entrant Boost coroutine?

I'm using Boost coroutine library, and I need my coroutine to be re-entrant.

This means I should be able to start the coroutine from the beginning multiple times.

What are some options?

My current workaround is to re-create the fresh coroutine every time:

boost::coroutines::coroutine<int>::pull_type *source = new boost::coroutines::coroutine<int>::pull_type(
            [&](boost::coroutines::coroutine<int>::push_type& sink){
    sink(0);
    cout << "Hello world!" << endl;
});
(*source)();

source = new boost::coroutines::coroutine<int>::pull_type(
            [&](boost::coroutines::coroutine<int>::push_type& sink){
    sink(0);
    cout << "Hello world!" << endl;
});
(*source)();

source = new boost::coroutines::coroutine<int>::pull_type(
            [&](boost::coroutines::coroutine<int>::push_type& sink){
    sink(0);
    cout << "Hello world!" << endl;
});
(*source)();

Upvotes: 1

Views: 569

Answers (2)

Tom Swirly
Tom Swirly

Reputation: 2790

I don't at all see what's wrong with creating a fresh coroutine every time - they're not expensive to create.

If you have a lot of data in your coroutine so it's expensive to construct, move it all off into some data class and pass a reference to it to your coroutine.

Upvotes: 0

olk
olk

Reputation: 400

Because the coroutines from boost.coroutine are stackfull you can't start them multiple times. It is not clear from your example what you want to do:

  • print "Hello world!" mutiple times -> use a loop inside the coro-fn
  • some kind of backtracking/checkpointing -> could be done with coroutiens, but needs some additional work

Upvotes: 1

Related Questions