Guest User

Untitled

a guest
Oct 23rd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "time"
  5. )
  6.  
  7. var forks [5]chan int
  8.  
  9. func main() {
  10. for i := 0; i < 5; i++ {
  11. forks[i] = make(chan int, 1)
  12. }
  13.  
  14. for i := 0; i < 4; i++ {
  15. go philosopher(i, &forks[i], &forks[i+1])
  16. }
  17.  
  18. go philosopher(4, &forks[0], &forks[4])
  19.  
  20. //just to keep main thread alive long enough
  21. for {
  22.  
  23. }
  24. }
  25.  
  26. func philosopher(id int, lower *chan int, higher *chan int) {
  27. for {
  28. if tryAcquire(lower) {
  29. if tryAcquire(higher) {
  30. println(id, "is eating")
  31. time.Sleep(time.Millisecond * 1000)
  32.  
  33. <-*higher
  34. <-*lower
  35. } else {
  36. <-*lower
  37. println(id, "is thinking")
  38. time.Sleep(time.Millisecond * 1000)
  39. }
  40. }
  41. }
  42. }
  43.  
  44. func tryAcquire(channel *chan int) bool {
  45. select {
  46. case *channel <- 1:
  47. return true
  48.  
  49. default:
  50. return false
  51. }
  52.  
  53. }
Add Comment
Please, Sign In to add comment