Concurrency Best Practices
Rules for safe, maintainable Rust concurrency - prefer message passing, minimize lock scope, and match the parallelism model to the workload.
Busca en todas las páginas de la documentación
Rules for safe, maintainable Rust concurrency - prefer message passing, minimize lock scope, and match the parallelism model to the workload.
Arc<Mutex<Everything>> to a service.RwLock only for read-heavy data. Writers dominate -> use Mutex or channels.Release/Acquire when publishing state.Arc<Mutex<LargeAppState>> god objects. Shard state or use actor tasks.thread::scope when borrowing stack data. Avoid unnecessary Arc clones for divide-and-conquer.JoinError and mutex poison. Do not silently unwrap in production paths.recv_timeout in tests and shutdown. Fail loud instead of hanging CI.Result per item in pipelines. Partial failure beats all-or-nothing panic.mutex.lock() or recv(). Use tokio::sync primitives in async code.spawn_blocking or Rayon from async. Keep latency predictable.std::sync::MutexGuard across .await. Breaks Send and stalls workers.Shared mutable cache without clear lock ordering plus concurrent writers - prefer channels or sharded locks.
Start near CPU cores for CPU work; for I/O-heavy sync servers, size to connection and pool limits, not num_cpus * 10 blindly.
If each update is an independent event, channels. If many readers need the same live struct, Arc<RwLock<T>>.
When invariants are simple, lock scope is tiny, and contention is low - counters, config snapshots, read-heavy caches.
Stress tests, inject sleeps, run tests multi-threaded, consider loom for lock-free algorithms.
Expose sequential API by default; optional parallel path behind feature flag if consumers may be single-threaded.
OnceLock, atomics, or lazy_static/std::sync::OnceLock - avoid unsynchronized static mut.
Document which thread calls FFI; Send/Sync on handles must match C library rules.
Thread names, tracing spans per worker, metrics on queue depth and lock wait time.
Replace shared mutation with a single owner thread and channel-based commands.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026