Skip to content

Instantly share code, notes, and snippets.

@klaeufer
Last active April 22, 2026 14:53
Show Gist options
  • Select an option

  • Save klaeufer/39d03158c4b766ce3c1c669f0d8ab930 to your computer and use it in GitHub Desktop.

Select an option

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 = 10) =
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()
// ^^^ comment out if using tryLock
// if rightFork.tryLock() then
println(f"$i eating")
Thread.sleep(Random.nextInt(delayInMs))
rightFork.unlock()
// end if
leftFork.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