Created
August 6, 2020 23:49
-
-
Save manju4ever/526348c08745b21c753b4c18b03bc866 to your computer and use it in GitHub Desktop.
coursera - dining philosophers problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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