kynnysmatto
kynnysmatto

Reputation: 3892

How can I call a coroutine from another coroutine in C++?

I have a long coroutine and I would like to divide it into smaller coroutines. Just like with regular functions, to make the code more clear. It should behave just like there was only one big coroutine with all the smaller ones happening consecutively.

I'm using #include <experimental/coroutine>.

I've been trying something like this:

resumable part1_coroutine()
{
    cout << "1" << endl;
    co_await suspend_always();
}

resumable part2_coroutine()
{
    cout << "2" << endl;
    co_await suspend_always();
}

resumable main_coroutine()
{
    cout << "main" << endl;
    part1_coroutine();
    part2_coroutine();
    co_await suspend_always();
}

But what seems to happen is that the part1_coroutine() and part2_coroutine() won't be executed at all.

Upvotes: 3

Views: 1831

Answers (2)

Jasiu
Jasiu

Reputation: 2734

Surprisingly, coroutines are not awaitables. As described in the standard, a coroutine can suspend only by interacting with awaitables (co_awaiting them). In order to call a coroutine from another coroutine, it has to be made into an awaitable. So you have to implement awaitable API on the object returned by the coroutine. So there is quite some amount of plumbing to build to make this work.

Upvotes: 2

Davis Herring
Davis Herring

Reputation: 39993

This is what co_await foo() does—give another coroutine foo a chance to make progress, suspending the current coroutine as necessary to wait on it to finish. If you just call a coroutine but don’t await it, you throw away the handle for that call to it, abandoning the call.

Upvotes: 3

Related Questions