Wiki
What is concurrency?
What concurrency focuses on is:
How multiple tasks are advanced together within the same period of time.
It does not require these tasks to actually execute simultaneously at the same instant.
1.An intuitive understanding
Suppose you are writing a program that needs to do several things at the same time:
接收网络数据
处理用户输入
更新内部状态
定时保存日志
These tasks should not completely block each other.
Even if the CPU has only one core, the operating system can allow different threads to take turns getting execution time, making these tasks appear to be progressing.
This is the core feeling of concurrency:
不是一件事做完再做下一件
而是多个任务交错推进
2.Concurrency is not equal to parallelism
Concurrency emphasizes the "way tasks are organized".
Parallelism emphasizes "whether they actually execute simultaneously."
Therefore:
并发程序不一定并行
并行执行通常需要并发任务作为基础
For example, running multiple threads on a single-core CPU is concurrency; only when multiple threads compute simultaneously on a multi-core CPU can it possibly be parallelism.
3.C++ Common concurrency tools in
C++ The standard library provides many concurrency tools, for example:
std::thread: Creating and managing threads;std::mutex: Protecting shared state;std::lock_guard/std::unique_lock: Managing locks with RAII;std::atomic: Performing atomic operations on individual objects;std::condition_variable: Making threads wait for a condition to occur;std::future/std::promise: Passing future results between threads or tasks;std::jthread/std::stop_token: More modern thread lifecycle and stop requests.
| Content | Learning Priority |
|---|---|
jthread + stop_token |
★★★★★ |
mutex + scoped_lock |
★★★★★ |
unique_lock |
★★★★★ |
atomic |
★★★★★ |
condition_variable |
★★★★☆ |
future / async |
★★★☆☆ |
promise |
★★☆☆☆ |
packaged_task |
★★☆☆☆ |
latch / barrier / semaphore |
★★☆☆☆ |
| Complex memory order / lock-free | ★☆☆☆☆ |
4.The most error-prone aspects of concurrency
The difficulty of concurrent code is usually not "starting a thread", but rather:
- When does a thread terminate?
- Who is responsible for waiting for a thread?
- Could an object used by a thread be destroyed prematurely?
- Could multiple threads accessing the same data cause a data race?
- Could multiple locks wait on each other and cause a deadlock?
Therefore, when learning concurrency, the focus is not on pursuing as many threads as possible, but first ensuring that the program behaves correctly.
5.Content corresponding to this chapter
The detailed chapters on concurrent programming that follow will continue to elaborate:
std::thread
mutex / lock_guard / unique_lock
std::atomic
condition_variable
future / async / promise
jthread / stop_token
semaphore / latch / barrier
These contents belong to C++ standard library concurrency fundamentals.