Concurrency and Async
Threads, message passing, locks, and async tasks. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Busca en todas las páginas de la documentación
Threads, message passing, locks, and async tasks. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Run a closure on a new OS thread.
use std::thread;
let h = thread::spawn(|| 1 + 1);
h.join().unwrap() // 2Multiple producer, single consumer messages.
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
tx.send(5).unwrap();
rx.recv().unwrap() // 5Exclusive access to shared data.
use std::sync::Mutex;
let m = Mutex::new(1);
{
let mut g = m.lock().unwrap();
*g += 1;
}
*m.lock().unwrap() // 2Atomic refcount for multi-thread ownership.
use std::sync::Arc;
let a = Arc::new(1);
let b = Arc::clone(&a);
*b // 1Async functions return impl Future; await to drive them.
async fn add(a: i32, b: i32) -> i32 { a + b }
// poll with a runtime: tokio::runtime or block_on
// conceptual: add(2, 3).await == 5Tokio schedules tasks on a multi-thread runtime.
// #[tokio::main]
// async fn main() {
// let h = tokio::spawn(async { 1 });
// assert_eq!(h.await.unwrap(), 1);
// }Threads often need move to take ownership of captures.
use std::thread;
let name = String::from("w");
thread::spawn(move || name.len()).join().unwrap() // 1Many readers or one writer.
use std::sync::RwLock;
let l = RwLock::new(1);
*l.read().unwrap() // 1Lock-free counters.
use std::sync::atomic::{AtomicUsize, Ordering};
let n = AtomicUsize::new(0);
n.fetch_add(1, Ordering::SeqCst);
n.load(Ordering::SeqCst) // 1Select on multiple channels with crossbeam/tokio select macros.
// tokio::select! { r = rx.recv() => ..., t = sleep => ... }Hold a handle to wait for thread completion.
use std::thread;
let h = thread::spawn(|| "done");
h.join().unwrap() // "done"Low-level thread parking - prefer channels for most code.
// thread::park(); other.thread().unpark();Scoped threads borrow stack data safely.
use std::thread;
let v = vec![1, 2];
thread::scope(|s| {
s.spawn(|| v.len());
});
v.len() // 2AsyncStream / StreamExt::next for async iteration (futures/tokio).
// while let Some(item) = stream.next().await { ... }Drive a future to completion on the current thread.
// futures::executor::block_on(async { 1 }) == 1
// or tokio Runtime::block_onStack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Revisado por Chris St. John·Última actualización: 18 jul 2026