Wiki
What is a coroutine?
Existing English translations were reused. 1 current source blocks remain in Simplified Chinese, without triggering paid translation.
Coroutines focus on:
How a function can pause and later resume execution from the point at which it paused.
It is a control flow tool; it is not equivalent to a thread, nor does it inherently imply parallelism.
1.An intuitive understanding
A normal function call is usually:
进入函数
一直执行
返回结果
函数结束
Coroutines are more like:
进入函数
执行一段
暂停
之后恢复
继续执行
再暂停或结束
This capability is very suitable for expressing asynchronous flows.
2.A coroutine is not a thread
Threads are scheduled by the operating system, and multiple threads may run simultaneously on multiple CPU cores.
Coroutines are usually cooperative:
协程自己在合适的位置暂停
调度器再恢复其他协程
Therefore:
多个协程可以在一个线程里交错执行
协程本身不保证并行
Only if the coroutine is backed by a thread pool or an asynchronous runtime can it be combined with parallel execution.
3.C++ Coroutine keywords
C++20 introduced language-level coroutine support, with common keywords including:
co_await: wait for an awaitable object, and possibly suspend the current coroutine;co_yield: yield a value, and suspend the current coroutine;co_return: return a result from the coroutine.
However, C++ the standard library only provides the low-level capabilities of the coroutine mechanism and does not directly provide a complete high-level asynchronous framework.
Therefore, when learning C++ coroutines, it is usually also necessary to understand them in conjunction with a specific library or runtime.
4.What scenarios are coroutines suitable for?
Coroutines are commonly found in:
- 异步 IO;
- 网络服务器;
- 定时任务;
- 生成器;
- 状态机;
- 需要把回调式代码写成顺序流程的场景。
5.Direction of the rest of this chapter
Currently, reserve a place for the coroutine concept first.
If further additions are made later, they can be expanded from these questions:
co_awaitWhat exactly are we waiting for?- What is the promise type?
- What is a coroutine handle?
- What is the difference between a generator and a task?
- How do coroutines combine with asynchronous IO and thread pools?
It will be much easier if you first understand that "a coroutine is a control flow that can be suspended and resumed," and then look at the specific syntax.