Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a coroutine returns to a suspended coroutine?

Suppose I have two coroutines, coroutine_a and coroutine_b. In coroutine_a it calls:

co_await awaiter_a;

The awaiter_a::await_suspend returns a coroutine handler of coroutine_b. As a result, coroutine_b is resumed. Then, in coroutine_b, it calls:

co_await awaiter_b;

The awaiter_b::await_suspend returns void. As a result, control should be returned to its caller/resumer coroutine_a. What will happen when control is returned to coroutine_a?

I think there are two options:

  1. coroutine_a returns to its caller.
  2. coroutine_a stays suspended until someone resumes it.

Which one is correct? Or is it something else?

like image 835
Machearn Avatar asked Feb 04 '26 15:02

Machearn


1 Answers

co_await awaiter_a;

To write this code into a function means that the function is waiting on a value that will be generated by awaiter_a. Therefore, this current function is not allowed to proceed until awaiter_a has generated that value.

If await_suspend returns a coroutine handle, this means that execution continues into that coroutine handle. However, this doesn't change the meaning of suspension; the current coroutine will stop until awaiter_a is ready to produce a value.

This effectively means that the new handle (from your coroutine_b) replaces the current handle (from your coroutine_a which just suspended itself).

If await_suspend returns nothing, then that just suspends the coroutine. So when coroutine_b does a co_await, it is suspended. But that's it. Control flow continues on from the caller of coroutine_a as if coroutine_a was suspended... because it was and still is suspended.

like image 114
Nicol Bolas Avatar answered Feb 06 '26 08:02

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!