Last active
March 4, 2016 20:30
-
-
Save larryprice/17c89ad14f2eefc0b4ed to your computer and use it in GitHub Desktop.
Dining philosophers with mutexes in go
This file contains 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" | |
"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