Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "time"
- )
- var forks [5]chan int
- func main() {
- for i := 0; i < 5; i++ {
- forks[i] = make(chan int, 1)
- }
- for i := 0; i < 4; i++ {
- go philosopher(i, &forks[i], &forks[i+1])
- }
- go philosopher(4, &forks[0], &forks[4])
- //just to keep main thread alive long enough
- for {
- }
- }
- func philosopher(id int, lower *chan int, higher *chan int) {
- for {
- if tryAcquire(lower) {
- if tryAcquire(higher) {
- println(id, "is eating")
- time.Sleep(time.Millisecond * 1000)
- <-*higher
- <-*lower
- } else {
- <-*lower
- println(id, "is thinking")
- time.Sleep(time.Millisecond * 1000)
- }
- }
- }
- }
- func tryAcquire(channel *chan int) bool {
- select {
- case *channel <- 1:
- return true
- default:
- return false
- }
- }
Add Comment
Please, Sign In to add comment