Code Example Template
Deep-Dive System Documentation
Thread-Safe Write Access: Mutex and RwLock
Since Arc<T> only permits read-only access across threads, you need a way to safely modify shared variables. Rust solves this via Interior Mutability using thread-safe lock wrappers.
1. Mutex (Mutual Exclusion)
Blocks access to all other threads while one thread holds the locked guard.
- Usage: Best when multiple threads frequently write to the shared state.
use std::sync::{Arc, Mutex};
use std::thread;
let active_app = Arc::new(Mutex::new(String::from("Desktop")));
let thread_app = Arc::clone(&active_app);
thread::spawn(move || {
let mut app_guard = thread_app.lock().unwrap(); // Blocks thread until lock acquired
*app_guard = String::from("Photoshop"); // Mutates shared state safely
}); // Lock guard dropped automatically here, unlocking active_app
2. RwLock (Reader-Writer Lock)
Allows any number of threads to read the data concurrently, but only one thread can write at a time.
- Usage: Best when you have frequent reads but rare writes.
Quick Reference Guide
let m = Mutex::new(0);
let mut num = m.lock().unwrap();