Last active
August 29, 2015 14:05
-
-
Save johnpmayer/e25162ec2e6d30f468e1 to your computer and use it in GitHub Desktop.
Dining Philosophers - Can't seem to make it deadlock
This file contains 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
extern crate sync; | |
use sync::Arc; | |
use sync::Mutex; | |
static N : uint = 5; | |
fn philosopher(seat : uint, vec : &Arc<Vec<Mutex<()>>>) { | |
let leftFork = seat; | |
let rightFork = (seat + 1) % N; | |
println!("Philosopher {} {} {}", seat, leftFork, rightFork); | |
let vec = vec.as_slice(); | |
let ref left = vec[leftFork]; | |
let ref right = vec[rightFork]; | |
loop { | |
left.lock(); | |
println!("Philosopher {} picks up fork {}",seat,leftFork); | |
right.lock(); | |
println!("Philosopher {} picks up fork {}",seat,rightFork); | |
println!("Philosopher {} is eating",seat); | |
} | |
} | |
fn main() { | |
let mut vec = Vec::new(); | |
for i in range(0, N) { | |
vec.push(Mutex::new(())); | |
} | |
let vec = Arc::new(vec); | |
for seat in range(0, N) { | |
let vec = vec.clone(); | |
spawn(proc() { | |
philosopher(seat, &vec) | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment