paranid5

I Wanna be A Philosopher

May 27th, 2021 (edited)
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.35 KB | None | 0 0
  1. import java.util.concurrent.Semaphore
  2. import kotlin.concurrent.thread
  3.  
  4. private object SemSys {
  5.     val sem = Semaphore(5)
  6. }
  7.  
  8. private data class Philosopher(val num: Int) {
  9.     private val name = "Philosopher $num"
  10.     var forks = 0
  11.  
  12.     private fun thinking() = println("$name has started thinking")
  13.  
  14.     private fun canEat() = forks == 2
  15.  
  16.     private fun eat() {
  17.         println("$name has started eating")
  18.         Thread.sleep(1000)
  19.         println("$name has finished eating")
  20.         returnForks()
  21.     }
  22.  
  23.     fun takeFork() {
  24.         when (forks) {
  25.             0 -> when {
  26.                 !SemSys.sem.tryAcquire() -> return
  27.                 else -> {
  28.                     forks++
  29.                     if (SemSys.sem.tryAcquire()) forks++
  30.                 }
  31.             }
  32.  
  33.             else -> when {
  34.                 !SemSys.sem.tryAcquire() -> return
  35.                 else -> forks++
  36.             }
  37.         }
  38.  
  39.         println("$name has taken fork (now: ${forks})")
  40.         if (canEat()) eat()
  41.     }
  42.  
  43.     private fun returnForks() {
  44.         SemSys.sem.release(2)
  45.         println("$name has returned forks")
  46.         forks = 0
  47.         thinking()
  48.     }
  49. }
  50.  
  51. fun main() {
  52.     (1..5).forEach {
  53.         val philosopher = Philosopher(it)
  54.  
  55.         thread {
  56.             while (true)
  57.                 philosopher.takeFork()
  58.         }
  59.     }
  60. }
Add Comment
Please, Sign In to add comment