Wiki
Concurrency, Parallelism, and Coroutines
Existing English translations were reused. 2 current source blocks remain in Simplified Chinese, without triggering paid translation.
This chapter discusses three easily confused concepts together:
- 并发(concurrency):多个任务在同一段时间内都在推进,重点是程序结构和任务协调。
- 并行(parallelism):多个任务在同一时刻真的同时执行,重点是利用多核或硬件能力提升吞吐。
- 协程(coroutine):一种可以暂停和恢复的函数,重点是控制流表达,常用于异步 IO。
They often appear together, but they are not the same thing.
并发:我有多个任务要安排
并行:我让多个任务真的同时跑
协程:我把一个任务写成可以暂停/恢复的流程
1.Learning Sequence
It is recommended to first read three concept sections:
| Order | Chapter | Purpose |
|---|---|---|
| 1 | What is concurrency | First understand multitasking, threads, shared state, synchronization, and data races |
| 2 | What is parallelism | Then understand simultaneous multi-core execution, task parallelism, data parallelism, and performance limits |
| 3 | What is a coroutine | Finally understand suspendable functions, cooperative scheduling, and asynchronous IO style |
Then proceed to detailed knowledge:
| Chapter | Current Status |
|---|---|
| Concurrent Programming | Expanded, including std::thread, mutex, atomic, condition variables, future, jthread, semaphore / latch / barrier |
| Parallel Programming | To be supplemented later |
| Coroutine Programming | To be supplemented later |
2.Why not just call it multithreading?
Multithreading is merely one way to achieve concurrency and parallelism.
For example:
- Multiple threads take turns executing on a single-core CPU; this is concurrency, but not parallelism in the strict sense;
- Multiple threads compute simultaneously on a multi-core CPU; this is concurrency, and may also be parallelism;
- Using coroutines within a single thread to handle multiple network requests is concurrency, but does not necessarily involve multiple threads;
- C++ Parallel algorithms may use thread pools or other execution mechanisms, but users do not necessarily manage threads directly.
Therefore, using "concurrency, parallelism, and coroutines" as the overall entry point for this chapter is more accurate than "multithreading."
3.Current Focus
At this stage, first solidly learn concurrent programming.
因为无论后面学习并行算法还是协程异步 IO,都绕不开这些基础问题:
- When does a task start and end?
- How are results passed between multiple tasks?
- Who owns shared data?
- How is shared data synchronized?
- How is cleanup handled on error, cancellation, and exit?
Once these questions are thought through clearly, looking at parallelism and coroutines will be much smoother.