-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (47 loc) · 1 KB
/
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
58
59
60
61
62
63
64
package main
import (
"fmt"
"sync"
"time"
)
type ChopStick struct {
sync.Mutex
}
type Philosopher struct {
number int
leftChopstick, rightChopstick *ChopStick
}
var host = make(chan int, 2)
var wg sync.WaitGroup
func (philosopher Philosopher) eat(c chan int) {
c <- philosopher.number
philosopher.leftChopstick.Lock()
philosopher.rightChopstick.Lock()
fmt.Printf("starting to eat %v\n", philosopher.number)
time.Sleep(500 * time.Millisecond)
fmt.Printf("finished eating %v\n", philosopher.number)
philosopher.leftChopstick.Unlock()
philosopher.rightChopstick.Unlock()
<-c
wg.Done()
}
func main() {
chopSticks := make([]*ChopStick, 5)
for i := 0; i < 5; i++ {
chopSticks[i] = new(ChopStick)
}
philosophers := make([]*Philosopher, 5)
for i := 0; i < 5; i++ {
philosophers[i] = &Philosopher{
i + 1,
chopSticks[i],
chopSticks[(i+1)%5]}
}
for i := 0; i < 3; i++ {
for j := 0; j < 5; j++ {
wg.Add(1)
go philosophers[j].eat(host)
}
}
wg.Wait()
}