Skip to content

Instantly share code, notes, and snippets.

@manju4ever
Created August 6, 2020 23:49
Show Gist options
  • Select an option

  • Save manju4ever/526348c08745b21c753b4c18b03bc866 to your computer and use it in GitHub Desktop.

Select an option

Save manju4ever/526348c08745b21c753b4c18b03bc866 to your computer and use it in GitHub Desktop.
coursera - dining philosophers problem
package main
import (
"fmt"
"sync"
)
type Fork struct{ id int }
type Philo struct {
id int
eatCount int
leftFork, rightFork *Fork
}
var waiter sync.WaitGroup = sync.WaitGroup{}
var locker sync.Mutex = sync.Mutex{}
func (philo *Philo) Eat() {
locker.Lock()
if philo.eatCount == 3 {
locker.Unlock()
waiter.Done()
return
}
philo.eatCount++
fmt.Printf(">> Philo %d eating - time: %d, L-fork-%d, R-fork-%d\n", philo.id, philo.eatCount, philo.leftFork.id, philo.rightFork.id)
waiter.Done()
locker.Unlock()
}
func main() {
philos := [5]*Philo{}
forks := [5]*Fork{}
for i := 0; i < 5; i++ {
forks[i] = &Fork{i + 1}
}
for i := 0; i < 5; i++ {
philos[i] = &Philo{i + 1, 0, forks[i], forks[(i+1)%5]}
}
for i := 0; i < 5; i++ {
// Every philo eats 3 times (async)
for j := 0; j < 3; j++ {
go philos[i].Eat()
waiter.Add(1)
}
}
waiter.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment