Skip to content

Instantly share code, notes, and snippets.

@larryprice
Last active March 4, 2016 20:30
Show Gist options
  • Save larryprice/17c89ad14f2eefc0b4ed to your computer and use it in GitHub Desktop.
Save larryprice/17c89ad14f2eefc0b4ed to your computer and use it in GitHub Desktop.
Dining philosophers with mutexes in go
package main
import (
"fmt"
"sync"
"time"
)
type Philosopher struct {
Name string
}
func (p *Philosopher) Think() {
time.Sleep(100 * time.Millisecond)
}
func (p *Philosopher) Eat(left, right *sync.Mutex) {
for {
left.Lock()
right.Lock()
fmt.Println(p.Name, "is eating!")
time.Sleep(time.Second)
left.Unlock()
right.Unlock()
p.Think()
}
}
func eat(p Philosopher, left, right *sync.Mutex) {
go p.Eat(left, right)
}
func main() {
p := []Philosopher{
Philosopher{"A"},
Philosopher{"B"},
Philosopher{"C"},
Philosopher{"D"},
Philosopher{"E"},
}
forks := []*sync.Mutex{}
for range p {
forks = append(forks, &sync.Mutex{})
}
for i, pp := range p {
eat(pp, forks[i], forks[(i+1)%len(forks)])
}
time.Sleep(10 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment