Rust Concurrency — Threads, Channels, and Shared State with Arc
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Concurrency. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust concurrency uses std::thread for OS threads, channels for message passing, and Arc
What You'll Learn
- Thread creation with std::thread
- Channels with mpsc
- Shared state with Arc
- Send and Sync traits
Why It Matters
Rust prevents data races at compile time. DodaZIP uses threads for parallel file processing. Firefox uses threads for rendering.
Real-World Use
Parallel data processing, web servers, background task execution, concurrent I/O.
use std::thread;
use std::sync::{Mutex, Arc, mpsc};
use std::time::Duration;
fn main() {
// Threads
let handle = thread::spawn(|| {
for i in 1..10 {
println!("Spawned: {}", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("Main: {}", i);
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
// Channels
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send(42).unwrap();
});
println!("Received: {}", rx.recv().unwrap());
// Shared state with Arc<Mutex>
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Counter: {}", *counter.lock().unwrap());
}
← Previous
Rust Error Handling Advanced — Custom Error Types, thiserror, and anyhow
Next →
Rust Async — Async/Await, Tokio, and Futures for Concurrent I/O
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro