Skip to content

Instantly share code, notes, and snippets.

@yackx
Created February 3, 2014 12:52
Show Gist options
  • Save yackx/8783302 to your computer and use it in GitHub Desktop.
Save yackx/8783302 to your computer and use it in GitHub Desktop.
Dining Philosophers
#!/usr/bin/env groovy
import static groovyx.gpars.GParsPool.withPool
import groovy.transform.*
import java.util.concurrent.*
@TypeChecked
class Philosopher {
enum State { THINKING, HUNGRY, EATING }
int MAX_TIME = 1 * 1000
int id
State state
Semaphore left, right
private void doItSomeTime() {
sleep(ThreadLocalRandom.current().nextLong(MAX_TIME))
}
private void dine() {
state = State.THINKING
println this
doItSomeTime()
state = State.HUNGRY
println this
left.acquire()
right.acquire()
state = State.EATING
doItSomeTime()
println this
right.release()
left.release()
dine()
}
@Override String toString() {
"#${id} is $state"
}
}
int PHILOSOPHER_COUNT = 5
List<Semaphore> forks = (1..PHILOSOPHER_COUNT).collect { new Semaphore(1) }
List<Philosopher> philosophers = (1..PHILOSOPHER_COUNT).collect { i ->
new Philosopher(id: i, left: forks[i - 1], right: forks[i % PHILOSOPHER_COUNT])
}
withPool(PHILOSOPHER_COUNT) {
philosophers.eachParallel { it.dine() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment