Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.Semaphore
- import kotlin.concurrent.thread
- private object SemSys {
- val sem = Semaphore(5)
- }
- private data class Philosopher(val num: Int) {
- private val name = "Philosopher $num"
- var forks = 0
- private fun thinking() = println("$name has started thinking")
- private fun canEat() = forks == 2
- private fun eat() {
- println("$name has started eating")
- Thread.sleep(1000)
- println("$name has finished eating")
- returnForks()
- }
- fun takeFork() {
- when (forks) {
- 0 -> when {
- !SemSys.sem.tryAcquire() -> return
- else -> {
- forks++
- if (SemSys.sem.tryAcquire()) forks++
- }
- }
- else -> when {
- !SemSys.sem.tryAcquire() -> return
- else -> forks++
- }
- }
- println("$name has taken fork (now: ${forks})")
- if (canEat()) eat()
- }
- private fun returnForks() {
- SemSys.sem.release(2)
- println("$name has returned forks")
- forks = 0
- thinking()
- }
- }
- fun main() {
- (1..5).forEach {
- val philosopher = Philosopher(it)
- thread {
- while (true)
- philosopher.takeFork()
- }
- }
- }
Add Comment
Please, Sign In to add comment