23.10 Concurrency
Concurrency
Overview
Rust provides safe concurrency using threads and message passing.
Topics
- Creating Threads
- Message Passing with Channels
- Shared State with Mutex
Examples
Threads
use std::thread;
let handle = thread::spawn(|| {
for i in 1..5 {
println!("Thread: {}", i);
}
});
handle.join().unwrap();
Channels
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("Hello from thread").unwrap();
});
let received = rx.recv().unwrap();
println!("{}", received);
Mutex
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::newnew(0);
let mut handles = vec![];
for _ in 0..5 {
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());