AgentSkillsCN

m07-concurrency

精通 C++ 并发编程。触发点:std::thread、jthread、原子操作、互斥锁、死锁、竞态条件、内存模型、协程、async。

SKILL.md
--- frontmatter
name: m07-concurrency
description: "Mastering C++ Concurrency. Triggers: std::thread, jthread, atomic, mutex, deadlock, race condition, memory model, coroutine, async."

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::async or Coroutines (C++20).

Error → Design Question

IssueDesign Question
Data RaceAre two threads accessing memory without a Happens-Before edge?
DeadlockDid you lock Mutex A then B, while another thread locked B then A?
False SharingAre independent atomics sitting on the same cache line?
Live LockAre threads spinning without progress?

Thinking Prompt

  1. Do I need a thread?

    • Short task? → std::async or Thread Pool.
    • Long background? → std::jthread.
  2. Is it shared state?

    • Yes? → Protect with std::mutex.
    • Is it small/primitive? → std::atomic.
  3. 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

ToolC++ VersionUse When
std::jthreadC++20Standard thread (auto-join).
std::atomicC++11Lock-free counters/flags.
std::mutexC++11Locking critical sections.
std::shared_mutexC++17Read-heavy workloads.
std::latchC++20Waiting for N tasks to start.
co_awaitC++20Async I/O (requires library).