Skip to content

Instantly share code, notes, and snippets.

@danlaudk
Created November 1, 2018 02:29
Show Gist options
  • Save danlaudk/89e82dbb320655361508bfce736f8ee9 to your computer and use it in GitHub Desktop.
Save danlaudk/89e82dbb320655361508bfce736f8ee9 to your computer and use it in GitHub Desktop.
dining philosophers
import com.twitter.concurrent.Offer
import com.twitter.util.{Await, Future}
import scala.concurrent.duration._
import scala.util.Random
import scala.collection.mutable.Seq
val deadline = 3 seconds fromNow
val r = new Random()
val numPhilosophers = 3
case class Spoon(toLeftOf: Int, var taken:Boolean)
case class Philosopher(n: Int, var eating:Boolean,var hungry:Boolean, var got:Seq[Boolean] = scala.collection.mutable.Seq((0 until numPhilosophers):_*).map(_ => false),
thinkTime: Int, eatTime: Int)
def whichSpoons(p:Philosopher, numPhilosophers:Int) : Seq[Int] = {
Seq(p.n, (p.n + 1) % numPhilosophers )
}
def whichPhilosophers(s :Spoon, numPhilosophers:Int) : Seq[Int] = {
Seq(s.toLeftOf, (s.toLeftOf - 1 + numPhilosophers) % numPhilosophers )
}
def run(thinkTime: Int, eatTime:Int, runforTime:Int):Unit = {
val spoons = (0 until numPhilosophers).map(i => new Spoon(i, taken = false))
(0 until numPhilosophers).par.foreach((x: Int) => {
val p = new Philosopher(x, false,false, thinkTime = thinkTime, eatTime = eatTime)
while(deadline.hasTimeLeft) {
//Thread.sleep(r.nextInt(100))
println("phil " + p.n + " is hungry")
var spoonsNotTaken:Boolean = whichSpoons(p, numPhilosophers).map( i => !(spoons(i).taken)).reduce(_&_)
if(spoonsNotTaken){
for( s <- whichSpoons(p, numPhilosophers).map(i => spoons(i))) {
if( !s.taken){
println("phil " + p.n + " taking sppon" + s.toLeftOf)
s.taken = true
p.got(s.toLeftOf) = true
}
Thread.sleep(500) // to get deadlock, catch breath after first spoon
}
} else println("phil " + p.n + "didn't see 2")
var gotSpoons = whichSpoons(p, numPhilosophers).map( i => p.got(i)).reduce(_&_)
if(gotSpoons) {
p.eating = true
println("phil " + p.n + " eats for " + p.eatTime + " s")
Thread.sleep(p.eatTime)
whichSpoons(p, numPhilosophers).map(i => {
spoons(i).taken = false
})
p.hungry = false
Thread.sleep(p.thinkTime)
} else p.hungry = true
}
})
}
run(3,5,5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment