This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Shared fate: threads in one process | |
| let data = Arc::new(Mutex::new(vec![])); | |
| thread::spawn({ | |
| let data = data.clone(); | |
| move || { | |
| let mut d = data.lock().unwrap(); | |
| panic!("oops"); // Mutex now poisoned for everyone | |
| } | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // High coordination: Mutex — consistent, slower | |
| let counter = Arc::new(Mutex::new(0)); | |
| { | |
| let mut c = counter.lock().unwrap(); // Wait for lock | |
| *c += 1; | |
| } | |
| // Less coordination: Atomic — faster, limited operations | |
| let counter = AtomicU64::new(0); | |
| counter.fetch_add(1, Ordering::Relaxed); // No waiting |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Local: in-memory HashMap — fast, not resilient | |
| let sessions: HashMap<SessionId, Session> = HashMap::new(); | |
| // Server restart = all sessions lost | |
| // Distributed: Redis cluster — slower, resilient | |
| let session = redis.get(session_id).await?; | |
| // Network hop, but survives server restarts |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Coarse: one connection handles everything sequentially | |
| fn handle_all(requests: Vec<Request>) { | |
| for req in requests { | |
| process(req); // Other threads sit idle | |
| } | |
| } | |
| // Fine: each request is a separate task | |
| for req in requests { | |
| tokio::spawn(async move { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Get the number of CPU cores | |
| NUM_CORES=$(nproc) | |
| # Function to perform CPU-intensive calculations | |
| cpu_stress() { | |
| echo "Starting task on process $$" | |
| start_time=$(date +%s.%N) | |
| echo "scale=5000; a(1)*4" | bc -l > /dev/null |