Skip to content

Instantly share code, notes, and snippets.

@klaeufer
Last active December 13, 2022 23:00
Show Gist options
  • Save klaeufer/39d03158c4b766ce3c1c669f0d8ab930 to your computer and use it in GitHub Desktop.
Save klaeufer/39d03158c4b766ce3c1c669f0d8ab930 to your computer and use it in GitHub Desktop.
import scala.util.Random
import java.util.concurrent.locks.ReentrantLock
def dinner(number: Int, delayInMs: Int) =
val forks = Array.fill(number)(new ReentrantLock)
// warning: running each philosopher in their own explicit Java thread
def phil(i: Int) = new Thread {
override def run(): Unit =
val leftFork = forks(i)
val rightFork = forks((i + 1) % number)
while true do
println(f"$i thinking")
Thread.sleep(Random.nextInt(delayInMs))
println(f"$i hungry, waiting for left fork $i")
leftFork.lock()
Thread.sleep(1)
println(f"$i got left, now waiting for right fork ${((i + 1) % number)}")
rightFork.lock()
println(f"$i eating")
Thread.sleep(Random.nextInt(delayInMs))
leftFork.unlock()
rightFork.unlock()
end while
end run
}
(0 until number).foreach(n => phil(n).start())
end dinner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment