Skip to content

Instantly share code, notes, and snippets.

@gterzian
Last active April 23, 2024 13:54
Show Gist options
  • Save gterzian/63ea7653171fc15c80a472dd2a500848 to your computer and use it in GitHub Desktop.
Save gterzian/63ea7653171fc15c80a472dd2a500848 to your computer and use it in GitHub Desktop.
/// 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