m07-concurrency
Mastering C++ Concurrency. Triggers: std::thread, jthread, atomic, mutex, deadlock, race condition, memory model, coroutine, async.
安装与使用
请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。
查看来源 ↗使用指南技能说明
C++ Concurrency
Core Question
How do threads communicate?
-
Shared State: Mutexes (
std::mutex) or Atomics (std::atomic). -
Coordination: Condition Variables (
std::condition_variable) or Latches/Semaphores (C++20). -
Tasks:
std::asyncor Coroutines (C++20).
Error → Design Question
| Issue | Design Question |
|---|---|
| Data Race | Are two threads accessing memory without a Happens-Before edge? |
| Deadlock | Did you lock Mutex A then B, while another thread locked B then A? |
| False Sharing | Are independent atomics sitting on the same cache line? |
| Live Lock | Are threads spinning without progress? |
Thinking Prompt
-
Do I need a thread?
- Short task? →
std::asyncor Thread Pool. - Long background? →
std::jthread.
- Short task? →
-
Is it shared state?
- Yes? → Protect with
std::mutex. - Is it small/primitive? →
std::atomic.
- Yes? → Protect with
-
Locks or Atomics?
- Logic requiring multiple steps? → Mutex (Atomic is only for single instructions).
- Simple flag/counter? → Atomic.
Trace Up / Down
-
Trace Up:
- Issue: "Random update values in counter."
-
Cause:
counter++is Read-Modify-Write, not atomic. Data race. -
Fix:
std::atomic<int>.
Quick Reference
| Tool | C++ Version | Use When |
|---|---|---|
std::jthread |
C++20 | Standard thread (auto-join). |
std::atomic |
C++11 | Lock-free counters/flags. |
std::mutex |
C++11 | Locking critical sections. |
std::shared_mutex |
C++17 | Read-heavy workloads. |
std::latch |
C++20 | Waiting for N tasks to start. |
co_await |
C++20 | Async I/O (requires library). |
使用示例
查看来源仓库中的使用示例与配置说明。
查看来源 ↗来源历史
- 收录时间
- 2026-03-11
- 索引更新时间
- 2026-03-11
- Branch
- main
收录与同步日期属于本站记录。源码修改历史请查看来源仓库。
GitHub ↗chat Comments (0)
Sign in to join the discussion and leave a comment.
No comments yet. Be the first to share your thoughts!