Rust — Concurrency
Creating threads
use std::thread;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("Spawned: {}", i);
thread::sleep(std::time::Duration::from_millis(100));
}
});
for i in 1..3 {
println!("Main: {}", i);
thread::sleep(std::time::Duration::from_millis(150));
}
handle.join().unwrap();
}
Message passing
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec!["hello", "from", "thread"];
for val in vals {
tx.send(val).unwrap();
thread::sleep(std::time::Duration::from_millis(100));
}
});
for received in rx {
println!("Got: {}", received);
}
}
Shared state
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
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!("Result: {}", *counter.lock().unwrap());
}
Send and Sync
// Send: can be transferred between threads
// Sync: can be shared between threads
// Arc<T> is Send + Sync if T is Send + Sync
// Mutex<T> is Sync
// Rc<T> is NOT Send or Sync
Mini Practice
Write Rust code that:
- Spawns multiple threads
- Uses channels for message passing
- Uses Arc<Mutex<T>> for shared state
- Demonstrates thread join
Up Next
Congratulations! You've completed the Rust fundamentals. Continue exploring advanced topics like async/await, traits in depth, and macro programming.
Related Topics
Frequently Asked Questions about Concurrency
What is Concurrency in Rust?
Concurrency is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Concurrency?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Concurrency.
Why is Concurrency important in Rust?
Concurrency is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.