rust-concurrency-primitives

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust Concurrency Primitives

Rust并发原语

Use this skill to design thread-based Rust concurrency with explicit ownership, sharing, and synchronization. Prefer the simplest primitive that matches the coordination requirement before adding shared mutable state.
使用本技能,基于明确的所有权、共享与同步规则设计基于线程的Rust并发实现。在引入共享可变状态前,优先选择符合协作需求的最简原语。

Core Workflow

核心工作流程

  1. Classify the work: independent fork-join, producer/consumer pipeline, shared state, one-time initialization, or low-level atomic coordination.
  2. Prefer owned data per thread. Add shared ownership only when data must be observed or mutated by multiple threads.
  3. Use
    std::thread::scope
    when child threads can borrow stack data and must finish before the function returns.
  4. Use channels for ownership transfer and pipelines. Use
    Arc<Mutex<T>>
    or
    Arc<RwLock<T>>
    only when shared state is the clearer model.
  5. Keep lock scopes short and never call user-controlled or blocking code while holding a lock unless that is the invariant being protected.
  6. Use
    OnceLock
    or
    LazyLock
    for thread-safe one-time initialization instead of ad hoc global mutable state.
  7. Treat atomics as a specialized tool. Use
    SeqCst
    by default until a weaker ordering is justified and documented.
  1. 对工作进行分类:独立分叉合并、生产者/消费者流水线、共享状态、一次性初始化或底层原子协作。
  2. 优先为每个线程使用自有数据。仅当数据必须被多线程观察或修改时,才添加共享所有权。
  3. 当子线程可以借用栈数据且必须在函数返回前完成时,使用
    std::thread::scope
  4. 使用通道进行所有权转移和流水线处理。仅当共享状态是更清晰的模型时,才使用
    Arc<Mutex<T>>
    Arc<RwLock<T>>
  5. 保持锁的作用域简短,除非要保护的不变量要求,否则持有锁时绝不要调用用户控制的代码或阻塞代码。
  6. 使用
    OnceLock
    LazyLock
    实现线程安全的一次性初始化,而非临时的全局可变状态。
  7. 将原子类型视为专用工具。默认使用
    SeqCst
    ,直到有充分理由并记录说明需要更弱的内存顺序。

Primitive Selection

原语选择

Read
references/threading-shared-state.md
before introducing a new shared state primitive or reviewing deadlock-prone code.
NeedPrimitive
Borrow local data into short-lived threads
std::thread::scope
Transfer work or results
std::sync::mpsc
or project channel crate
Shared read/write state
Arc<Mutex<T>>
Many readers, rare writers
Arc<RwLock<T>>
Wait for condition changes
Condvar
with
Mutex
One-time global initialization
LazyLock
or
OnceLock
Counters, flags, lock-free coordination
std::sync::atomic
在引入新的共享状态原语或评审易出现死锁的代码前,请阅读
references/threading-shared-state.md
需求原语
将本地数据借用至短期线程
std::thread::scope
传递任务或结果
std::sync::mpsc
或项目通道 crate
共享读写状态
Arc<Mutex<T>>
多读取、少写入
Arc<RwLock<T>>
等待条件变化搭配
Mutex
使用
Condvar
全局一次性初始化
LazyLock
OnceLock
计数器、标志、无锁协作
std::sync::atomic

Safety And Review Rules

安全与评审规则

  • Require
    Send
    for values crossing thread boundaries and
    Sync
    for shared references used from multiple threads.
  • Decide whether poisoning should propagate panic or recover with
    PoisonError::into_inner
    .
  • Establish a lock ordering when more than one lock can be acquired.
  • Prefer
    Arc::clone(&value)
    over
    value.clone()
    when the cloned value is an ownership handle and readability matters.
  • Use Rayon for data parallel iteration when the problem is pure CPU data parallelism and the project already accepts that dependency.
  • 要求跨线程边界的值实现
    Send
    ,多线程使用的共享引用实现
    Sync
  • 决定是否让锁中毒传播恐慌,或是使用
    PoisonError::into_inner
    恢复。
  • 当需要获取多个锁时,确立锁的获取顺序。
  • 当克隆的是所有权句柄且可读性很重要时,优先使用
    Arc::clone(&value)
    而非
    value.clone()
  • 当问题属于纯CPU数据并行且项目已引入该依赖时,使用Rayon进行数据并行迭代。

Tests

测试

  • Add deterministic tests around final state, message counts, and shutdown.
  • Use barriers, channels, or scoped threads to coordinate tests; avoid sleeps.
  • Add at least one test for panic, dropped sender/receiver, or cancellation behavior when the code depends on it.
  • 围绕最终状态、消息数量和关闭逻辑添加确定性测试。
  • 使用屏障、通道或作用域线程协调测试;避免使用睡眠等待。
  • 当代码依赖于恐慌、发送者/接收者被丢弃或取消行为时,至少添加一个相关测试。