Concurrency safety guarantees help your program avoid mistakes when many parts run at the same time. This keeps your program correct and prevents crashes or wrong results.
Concurrency safety guarantees in Rust
use std::sync::{Arc, Mutex};
let data = Arc::new(Mutex::new(0));
// Arc allows sharing ownership safely
// Mutex allows only one thread to access data at a timeArc stands for Atomic Reference Counting. It lets multiple parts share ownership safely.
Mutex is a lock that makes sure only one part can change data at once.
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(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());use std::sync::RwLock; let data = RwLock::new(5); { let r = data.read().unwrap(); println!("Read data: {}", *r); } { let mut w = data.write().unwrap(); *w += 1; println!("Updated data: {}", *w); }
This program creates 10 threads. Each thread safely adds 1 to the shared counter using Mutex and Arc. The final value shows the total increments.
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!("Final counter value: {}", *counter.lock().unwrap());
}Rust's ownership and type system help catch concurrency mistakes at compile time.
Mutex can cause your program to wait if another part is using the data, so use it carefully.
Arc is needed to share data safely between threads because normal references can't be shared safely.
Concurrency safety guarantees prevent bugs when multiple parts run at the same time.
Use Arc to share ownership and Mutex or RwLock to control access to shared data.
Rust helps you write safe concurrent code by checking rules before running your program.