-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
57 lines (43 loc) · 911 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"fmt"
"sync"
"time"
)
type fork struct{ sync.Mutex }
type philosopher struct {
id int
leftFork, rightFork *fork
}
func (p philosopher) eat() {
for j := 0; j < 3; j++ {
p.leftFork.Lock()
p.rightFork.Lock()
say("eating", p.id)
time.Sleep(time.Second)
p.rightFork.Unlock()
p.leftFork.Unlock()
say("finished eating", p.id)
time.Sleep(time.Second)
}
eatWgroup.Done()
}
func say(action string, id int) {
fmt.Printf("Philosopher #%d is %s\n", id+1, action)
}
var eatWgroup sync.WaitGroup
func main() {
count := 5
forks := make([]*fork, count)
for i := 0; i < count; i++ {
forks[i] = new(fork)
}
philosophers := make([]*philosopher, count)
for i := 0; i < count; i++ {
philosophers[i] = &philosopher{
id: i, leftFork: forks[i], rightFork: forks[(i+1)%count]}
eatWgroup.Add(1)
go philosophers[i].eat()
}
eatWgroup.Wait()
}