Boost coroutines with global yield

428 Views Asked by At

Since my initial question got flagged because I asked two questions in one I'm gonna be more specific.

I want to use the boost library for context switching within a single thread. Therefore my plan is to use coroutines. But ideally I do not want to change the tranfer parameters or the function type of an existing function.

Is there a way to declare yield as a global variable for each task? Then I would not have an additional transfer parameter.

#include <iostream>
#include <boost/coroutine2/all.hpp>

using namespace std;
using namespace boost::coroutines2;
void task1(coroutine<void>::push_type& yield);
void task2(coroutine<void>::push_type& yield);

coroutine<void>::pull_type coro1(task1);
coroutine<void>::pull_type coro2(task2);

void task2(coroutine<void>::push_type& yield) {
    cout << "> Start task2\n";
    yield();
    cout << "> Continue task2\n";
    yield();
    cout << "> Finish task2\n";

}

void task1(coroutine<void>::push_type& yield) {
    cout << "> Start task1\n";
    yield();
    cout << "> Continue task1\n";
    yield();
    cout << "> Finish task1\n";
}

int main(void) {
    coro1();
    coro2();
    coro1();
    coro2();
    return 0;
}

Output:

> Start task1
> Start task2
> Continue task1
> Continue task2
> Finish task1
> Finish task2

Note: I also looked in the source code, but I don't really understand the templates etc. (I'm a C++ beginner). Maybe someone already has experience with this topic and can help me.

0

There are 0 best solutions below