Last active
April 23, 2024 13:54
-
-
Save gterzian/63ea7653171fc15c80a472dd2a500848 to your computer and use it in GitHub Desktop.
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
/// Implementation of the algorithm described at | |
/// https://lamport.azurewebsites.net/pubs/teaching-concurrency.pdf | |
use std::collections::HashMap; | |
use std::sync::{Arc, Mutex}; | |
#[derive(Eq, PartialEq, Hash, Clone)] | |
struct ProcessId(i32); | |
#[derive(Debug, Clone)] | |
enum Value { | |
Zero, | |
One, | |
} | |
const N: i32 = 10; | |
fn main() { | |
let x: Arc<Mutex<HashMap<ProcessId, Value>>> = Default::default(); | |
let mut handles = Vec::new(); | |
for p in 0..N - 1 { | |
let x = x.clone(); | |
let process_id = ProcessId(p); | |
{ | |
let mut x = x.lock().unwrap(); | |
x.insert(process_id.clone(), Value::Zero); | |
} | |
let handle = std::thread::spawn(move || { | |
let y = { | |
// x [i] : = 1; | |
let mut x = x.lock().unwrap(); | |
*x.get_mut(&process_id).unwrap() = Value::One; | |
// y[i] : = x [(i − 1) mod N ] | |
let prev = (p - 1) % N; | |
x.get(&ProcessId(prev)).cloned() | |
}; | |
println!("y = {:?}", y); | |
}); | |
handles.push(handle); | |
} | |
for handle in handles { | |
handle.join().unwrap(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment