Skip to main content
1 of 2
Levon
  • 295
  • 1
  • 2
  • 9

Dining philosophers problem in Go

I'm new in Golang and haven't done concurrency in a bit. I would love to hear your opinion on my Dining problem Go solution.

package main

import "fmt"
import "sync"
import "time"

const NumPhilosophers = 5
var phi [NumPhilosophers]int
var forks [NumPhilosophers]sync.Mutex

func startPhilosopher(number int, c chan string){
    left, right := (number+1)%NumPhilosophers, number
    min, max := left,right
    if min > max {
        min, max = max, min
    }

    for i := 0; i < 4; i++ {
        c <-"Thinking " + time.Now().Round(0).String()
        forks[min].Lock()
        forks[max].Lock()

        c <- "Eating " + time.Now().Round(0).String()

        forks[max].Unlock()
        forks[min].Unlock()
    }
    close(c)
}

func main() {
    var ch [NumPhilosophers]chan string
    for i := 0; i < NumPhilosophers; i++ {
        phi[i] = i
        ch[i] = make(chan string)
        go startPhilosopher(i, ch[i])
    }

    for a := 0; a < NumPhilosophers; a++ {
        fmt.Println(a)
        for i := range ch[a] {
            fmt.Println(i)
        }
    }
}
```
Levon
  • 295
  • 1
  • 2
  • 9