{"data":{"slug":"discovered-9bb9782e9da93a00f0cb3fb564fe9fd01c92cd92177b86bb","title":"Rust Concurrency","summary":"Design, implement, diagnose, and test Rust concurrency and parallelism with threads, Send and Sync, locks, atomics, channels, Tokio, Rayon, Crossbeam, bounded backpressure, actor ownership, task supervision, graceful shutdown, runtime diagnostics, and Loom model tests. Use when users ask about shared state, deadlocks, async tasks, CPU parallelism, high concurrency, daemon resource budgets, slow consumers, worker pools, lock-free structures, or concurrent correctness.","url":"https:\/\/skillshunter.net\/skills\/discovered-9bb9782e9da93a00f0cb3fb564fe9fd01c92cd92177b86bb","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-9bb9782e9da93a00f0cb3fb564fe9fd01c92cd92177b86bb","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-9bb9782e9da93a00f0cb3fb564fe9fd01c92cd92177b86bb.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-9bb9782e9da93a00f0cb3fb564fe9fd01c92cd92177b86bb\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Prerequisite: Understanding of Rust ownership as described in the Rust book. Before writing concurrency code, classify the workload and define concurrency budgets, including maximum connections, in-flight tasks, queue capacity, item size, timeouts, memory, CPU pools, and shutdown deadlines.","instructions":"---\ndescription: Design, implement, diagnose, and test Rust concurrency and parallelism with threads, Send and Sync, locks, atomics, channels, Tokio, Rayon, Crossbeam, bounded backpressure, actor ownership, task supervision, graceful shutdown, runtime diagnostics, and Loom model tests. Use when users ask about shared state, deadlocks, async tasks, CPU parallelism, high concurrency, daemon resource budgets, slow consumers, worker pools, lock-free structures, or concurrent correctness.\nlicense: Apache-2.0\nmetadata:\n    github-path: skills\/rust-concurrency\n    github-pinned: b8a6af74af28ee86b8cbbbc3075cde0b31a5155e\n    github-ref: b8a6af74af28ee86b8cbbbc3075cde0b31a5155e\n    github-repo: https:\/\/github.com\/full-stack-skills\/rust-skills\n    github-tree-sha: 6303908c90112c1a345656a28282e48716085127\nname: rust-concurrency\n---\n# Rust Concurrency\n\n> Based on the standard library `std::thread`, `std::sync`, and `std::sync::atomic` modules, along with the Async Book. Use when designing, debugging, load-testing, or reviewing threaded and async Rust code; cancellation, task ownership, lock scope, runtime sizing, queues, overload management, and message passing.\n\n## Capability Boundaries\n\n### \u2705 Strengths\n1. OS threads (`thread::spawn`, `Builder`, `join`, scoped threads, move closures)\n2. Synchronization primitives (Mutex, RwLock, Barrier, Condvar, OnceLock, LazyLock)\n3. Atomic types (AtomicBool\/Isize\/Usize, load\/store\/fetch_add\/swap\/compare_exchange, Ordering)\n4. Channels (`mpsc`: multi-producer single-consumer, Receiver, Sender)\n5. `Send` \/ `Sync` trait system (automatic derivation and manual implementation)\n6. async\/await syntax with the Future trait\n7. Tokio runtime (`tokio::main`, `tokio::spawn`, select!, JoinSet)\n8. Async I\/O foundations (`tokio::fs`, `tokio::net`, `tokio::io`)\n9. Bounded queues, backpressure, slow consumers, concurrency limits and overload strategies\n10. Task supervision, connection lifecycles, cancellation safety and graceful shutdown\n11. CPU-bound data parallelism and dedicated Rayon pools\n12. Crossbeam channels, queues, work-stealing deques, and scoped threads\n13. Read-heavy snapshots, sharded maps, caches, and alternative locks when measurements justify them\n14. Loom model checking and Tokio runtime diagnostics\n\n### \u26a0\ufe0f Prerequisites\n1. Understanding [Rust ownership](https:\/\/doc.rust-lang.org\/book\/ch04-00-understanding-ownership.html)\n\n### \u274c Inapplicable Scenarios\n1. Unsafe code concurrent execution \u2192 consult [The Rustonomicon](https:\/\/doc.rust-lang.org\/nomicon\/) for unsafe invariants\n2. Basic ownership\/borrowing \u2192 consult [rust-best-practices](..\/rust-best-practices\/SKILL.md)\n\n## When to Use\n\n- \"Process data with multiple threads\"\n- \"How to write async\/await\"\n- \"Tokio runtime usage\"\n- \"Shared data between threads\"\n- \"Avoid data races\"\n- \"Rate limiting and graceful shutdown in high-concurrency services\"\n- \"Tokio channel backlog or slow consumers\"\n\n## Data Privacy\n\nThis skill does not collect, store, or transmit any user data.\n\n---\n\n## I. OS Threads\n\n```rust\nuse std::thread;\n\nlet handle = thread::spawn(move || {\n    println!(\"Hello from thread!\");\n});\nhandle.join().unwrap();\n\n\/\/ Thread with configuration\nlet builder = thread::Builder::new()\n    .name(\"worker\".into())\n    .stack_size(1024 * 1024);\nlet handle = builder.spawn(move || { \/* ... *\/ }).unwrap();\n\n\/\/ scoped threads (1.63+)\nlet mut v = vec![1, 2, 3];\nthread::scope(|s| {\n    s.spawn(|| {\n        v.push(4); \/\/ borrow, no move required\n    });\n});\nprintln!(\"{v:?}\"); \/\/ v remains usable\n```\n\n## II. Synchronization Primitives\n\n```rust\nuse std::sync::{Arc, Mutex, RwLock, Barrier, OnceLock, LazyLock};\n\n\/\/ Mutex (mutual exclusion lock)\nlet counter = Arc::new(Mutex::new(0));\nlet mut handles = vec![];\n\nfor _ in 0..10 {\n    let counter = Arc::clone(&counter);\n    handles.push(thread::spawn(move || {\n        let mut num = counter.lock().unwrap();\n        *num += 1;\n    }));\n}\n\n\/\/ RwLock (read-write lock)\nlet data = Arc::new(RwLock::new(vec![1, 2, 3]));\n{\n    let read = data.read().unwrap();\n    assert_eq!(read.len(), 3);\n} \/\/ Drop the read guard before taking the write lock.\ndata.write().unwrap().push(4);\n\n\/\/ OnceLock (thread-safe lazy initialization)\nstatic CONFIG: OnceLock<String> = OnceLock::new();\nlet config = CONFIG.get_or_init(|| load_config());\n\n\/\/ LazyLock\nstatic CACHE: LazyLock<HashMap<String, Data>> = LazyLock::new(HashMap::new);\n```\n\n## III. Atomic Operations\n\n```rust\nuse std::sync::atomic::{\n    AtomicBool, AtomicU64, Ordering\n};\n\nstatic COUNTER: AtomicU64 = AtomicU64::new(0);\nCOUNTER.fetch_add(1, Ordering::SeqCst);\n\nstatic READY: AtomicBool = AtomicBool::new(false);\nREADY.store(true, Ordering::Release);\nlet ready = READY.load(Ordering::Acquire);\n\n\/\/ Ordering levels\n\/\/ Relaxed \u2014 no ordering guarantees (only atomicity)\n\/\/ Release \u2014 write visibility\n\/\/ Acquire \u2014 read visibility\n\/\/ AcqRel \u2014 both reads and writes visible\n\/\/ SeqCst \u2014 global sequential order (strongest, but not automatically default; explicit Ordering required for atomic operations)\n```\n\n## IV. Channels\n\n```rust\nuse std::sync::mpsc;\n\nlet (tx, rx) = mpsc::channel();\nthread::spawn(move || {\n    tx.send(1).unwrap();\n    tx.send(2).unwrap();\n});\nfor received in rx {\n    println!(\"Got: {received}\");\n}\n\n\/\/ Multi-producer scenario\nlet (tx, rx) = mpsc::channel();\nlet tx1 = tx.clone();\n```\n\n## V. async\/await\n\n```rust\nuse tokio::time;\n\nasync fn do_work(id: u32) -> &'static str {\n    time::sleep(time::Duration::from_secs(1)).await;\n    println!(\"Task {id} done\");\n    \"ok\"\n}\n\n#[tokio::main]\nasync fn main() {\n    \/\/ Concurrent execution\n    let (r1, r2) = tokio::join!(do_work(1), do_work(2));\n\n    \/\/ select!\n    tokio::select! {\n        result = do_work(1) => println!(\"task1: {result}\"),\n        result = do_work(2) => println!(\"task2: {result}\"),\n    }\n\n    \/\/ tokio::spawn\n    let handle = tokio::spawn(do_work(3));\n    handle.await.unwrap();\n}\n```\n\n## VI. Send \/ Sync\n\n```rust\n\/\/ T is Send if its ownership can be transferred across threads\n\/\/ &T is Sync if it can be shared references across threads\n\n\/\/ Types that are both Send + Sync: Arc<Mutex<T>>, i32, &'static str\n\/\/ !Send types: Rc<T>, *const T\n\/\/ !Sync types: RefCell<T>, Cell<T>\n\n\/\/ Manual implementations are unsafe contracts. Do not add them merely to\n\/\/ satisfy a compiler error; prove aliasing, lifetime, and thread-safety first.\n```\n\n## VII. Select the Execution Model\n\n| Workload | Default starting point | Avoid |\n|---|---|---|\n| Many readiness-driven network operations | Tokio tasks with bounded admission | One task or buffer per unbounded input |\n| CPU-heavy independent items | Rayon parallel iterators or a dedicated pool | Running long CPU work on Tokio workers |\n| Blocking filesystem, FFI, or legacy APIs | Bounded `spawn_blocking` submissions or a dedicated pool | Treating Tokio's blocking queue as backpressure |\n| Synchronous MPMC messaging or work stealing | Crossbeam channels, queues, or deques | Selecting lock-free structures without measurement |\n| Small shared state with short critical sections | `std::sync` locks | Holding guards across `.await` or callbacks |\n| Read-mostly immutable snapshots | `ArcSwap` after profiling | A concurrent map for every read-heavy value |\n| Shared keyed mutable state | Sharded ownership or `DashMap` after contention tests | Multi-key operations without an atomicity design |\n| Expiring concurrent cache | Moka with explicit capacity and eviction policy | An unbounded map called a cache |\n\nTokio is primarily for I\/O concurrency; Rayon is for CPU parallelism. Mixing them requires an explicit handoff, independent concurrency limits, and shutdown ownership. Read [Concurrency Tool Selection](references\/concurrency-tool-selection.md) before introducing a third-party primitive.\n\n## Workflow\n\n1. **Classify the workload** \u2014 separate readiness-driven I\/O, CPU parallelism, blocking calls, synchronization, and durable messaging before selecting a runtime or primitive.\n2. **Write concurrency budgets** \u2014 define maximum connections, in-flight tasks, queue capacity, item size, timeouts, memory, CPU pools, and shutdown deadlines.\n3. **Determine state ownership** \u2014 prefer partitioned or single-writer ownership; share state only with an explicit atomicity and lock-ordering contract.\n4. **Select communication semantics** \u2014 choose bounded point-to-point, request\/reply, latest-value, lossy broadcast, or durable replay deliberately; specify queue-full and receiver-lag behavior.\n5. **Supervise execution** \u2014 retain task or thread handles, propagate failure, contain panic, prevent orphan work, and define caller-cancellation behavior.\n6. **Design graceful shutdown** \u2014 stop admission, close producers, publish cancellation, join within a deadline, flush required state, and return unresolved failures.\n7. **Measure before tuning** \u2014 record throughput, p50\/p95\/p99 latency, queue depth, saturation, task poll time, wakeups, lock wait, CPU, allocations, and RSS.\n8. **Verify the model** \u2014 test overload and cancellation, use Loom for small synchronization state machines, and use tokio-console or tracing for runtime stalls. Read [Concurrency Testing and Diagnostics](references\/concurrency-testing-and-diagnostics.md).\n\n## Gotchas\n\n1. Mutex::lock() returns a `MutexGuard`; do not await before dropping to avoid deadlocks\n2. tokio::spawn's Future must be both Send and 'static; non-Send references will cause compilation errors\n3. Async closures capture ownership differently than regular closures \u2014 use the move keyword explicitly for transfer of state\n4. Cancelled Futures in select! branches do not execute cleanup logic directly before dropping\n5. Atomic Ordering is not relational semantics; misuse of Relaxed can lead to unexpected memory ordering issues\n6. broadcast lag is distinct from normal success paths; must choose between discarding, rebuilding snapshots, disconnecting slow consumers, or persistently replaying events\n7. max_blocking_threads limits only the number of blocking threads and does not provide backpressure for submission queues; high-cost tasks require Semaphore or bounded queues\n8. JoinSet returns results in completion order; if API requires input ordering, carry indices through to restore sequence during aggregation\n9. `DashMap`, `parking_lot`, `ArcSwap`, and lock-free queues change semantics as well as performance; benchmarks do not replace invariant review\n10. Loom sees only synchronization performed through Loom-aware types and can suffer state-space explosion; keep models small and deterministic\n11. Rayon work may outlive the async caller unless cancellation and pool ownership are designed explicitly\n\n## On-Demand Resources\n\n- [Concurrency Examples](examples\/examples.md)\n- [Type & Tool Quick Reference](references\/references.md)\n- [Concurrency Tool Selection](references\/concurrency-tool-selection.md): Read when choosing Tokio, Rayon, Crossbeam, locks, sharded maps, snapshots, or caches.\n- [Concurrency Testing and Diagnostics](references\/concurrency-testing-and-diagnostics.md): Read when proving synchronization correctness, diagnosing runtime stalls, or load-testing overload and shutdown.\n- [Production Async Service Patterns](references\/production-async-services.md): Read when designing actors, backpressure, slow consumers, task supervision, runtime configuration, and shutdown protocols.\n- `examples\/golden-threads\/`: CI-built scoped thread examples\n\n## Official References\n\n- [std::thread Documentation](https:\/\/doc.rust-lang.org\/std\/thread\/)\n- [std::sync Documentation](https:\/\/doc.rust-lang.org\/std\/sync\/)\n- [std::sync::atomic Documentation](https:\/\/doc.rust-lang.org\/std\/sync\/atomic\/)\n- [Async Book](https:\/\/rust-lang.github.io\/async-book\/)\n- [Tokio Guide](https:\/\/tokio.rs\/tokio\/tutorial)\n- [Rayon](https:\/\/docs.rs\/rayon\/)\n- [Crossbeam](https:\/\/docs.rs\/crossbeam\/)\n- [Loom](https:\/\/docs.rs\/loom\/)\n","use_cases":["Process data with multiple threads","Write async\/await code","Use the Tokio runtime","Share data between threads","Avoid data races","Implement rate limiting and graceful shutdown in high-concurrency services"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/sajaddp\/sonjoo-seo-audit\/blob\/b53a2eae486acf635a0b1dbd76be236343deb4b2\/.agents\/skills\/rust-concurrency\/SKILL.md","source_commit":"b53a2eae486acf635a0b1dbd76be236343deb4b2","license":null,"version":null,"listing_approved_at":"2026-11-30","created_at":"2026-11-29T11:05:07.000000Z","updated_at":"2026-11-30T06:52:12.000000Z","seo_title":"Rust Concurrency Skill","seo_description":"Learn to design, implement, and test Rust concurrency and parallelism with threads, Send and Sync, locks, atomics, channels, Tokio, Rayon, Crossbeam, and more.","seo_keywords":["Rust concurrency","Rust threads","Rust Send Sync","Rust locks","Rust atomics","Rust channels","Tokio runtime","Rayon parallelism"]}}