Last active
December 13, 2022 23:00
-
-
Save klaeufer/39d03158c4b766ce3c1c669f0d8ab930 to your computer and use it in GitHub Desktop.
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
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