
上QQ阅读APP看书,第一时间看更新
Coroutines
Coroutines are special functions able to stop at any defined point of execution and resume later. Coroutines extend the language with the following new keywords:
- co_await suspends the execution of the coroutine.
- co_yield suspends the execution of the coroutine while also returning a value.
- co_return is similar to the regular return keyword; it finishes the coroutine and returns a value. Take a look at the following classic example:
generator<int> step_by_step(int n = 0) {
while (true) {
co_yield n++;
}
}
A coroutine is associated with a promise object. The promise object stores and alerts the state of the coroutine. We will dive deeper into coroutines in Chapter 8, Concurrency and Multithreading.