-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdining.go
85 lines (64 loc) · 1.22 KB
/
dining.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"sync"
)
var wg = sync.WaitGroup{}
type Host struct {
seenEating int
mu sync.Mutex
}
func (h *Host) permitEating() bool {
if h.seenEating >= 2 {
return false;
}
h.mu.Lock();
h.seenEating += 1;
h.mu.Unlock();
return true;
}
func (h *Host) serveAnother() {
h.mu.Lock()
h.seenEating -= 1
h.mu.Unlock();
}
type Chopstick struct {
mu sync.Mutex
}
type Philosopher struct {
leftCS, rightCS *Chopstick
host Host
number int
helpingsEaten int
}
func (p Philosopher) eat(helpings int) {
for i := 0; i < helpings; i++ {
for !p.host.permitEating() {}
p.leftCS.mu.Lock()
p.rightCS.mu.Lock()
fmt.Println("Starting to eat ", p.number)
p.leftCS.mu.Unlock()
p.rightCS.mu.Unlock()
p.helpingsEaten += 1;
fmt.Println("Finishing eating ", p.number)
p.host.serveAnother()
}
wg.Done();
}
func main() {
tonightsHost := Host{}
// Creates chopsticks and philosophers
CSticks := make([] *Chopstick, 5)
for i := 0; i < 5; i++ {
CSticks[i] = new(Chopstick)
}
philos := make([] *Philosopher, 5)
for i := 0; i < 5; i++ {
philos[i] = &Philosopher{CSticks[i], CSticks[(i+1)%5], tonightsHost, i + 1, 0}
}
wg.Add(5);
for i := 0; i < 5; i++ {
go philos[i].eat(3)
}
wg.Wait();
}