-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphilos.go
More file actions
129 lines (116 loc) · 2.33 KB
/
philos.go
File metadata and controls
129 lines (116 loc) · 2.33 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"fmt"
"sync"
)
type chopStick struct {
sync.Mutex
}
type host struct {
eatingPhiloNumbers []int
mut sync.Mutex
}
func (h *host) isEating(philoNum int) bool {
for _, num := range h.eatingPhiloNumbers {
if num == philoNum {
return true
}
}
return false
}
func (h *host) wantToEat(ph *philo) bool {
if len(h.eatingPhiloNumbers) == 2 {
return false
}
var numNeighbor1 int
var numNeighbor2 int
if ph.number == 1 {
numNeighbor1 = 2
numNeighbor2 = 5
} else if ph.number == 5 {
numNeighbor1 = 1
numNeighbor2 = 4
} else {
numNeighbor1 = ph.number + 1
numNeighbor2 = ph.number - 1
}
h.mut.Lock()
defer h.mut.Unlock()
neighborsNotEat := !h.isEating(numNeighbor1) && !h.isEating(numNeighbor2)
if neighborsNotEat {
h.eatingPhiloNumbers = append(h.eatingPhiloNumbers, ph.number)
return true
}
return false
}
func (h *host) endEat(philoNum int) {
h.mut.Lock()
for i, num := range h.eatingPhiloNumbers {
if num == philoNum {
arr := h.eatingPhiloNumbers
h.eatingPhiloNumbers = append(arr[:i], arr[i+1:]...)
}
}
h.mut.Unlock()
}
type philo struct {
host *host
number int
leftCP *chopStick
rightCP *chopStick
countLeft int
isEating bool
}
func (ph *philo) tryToEat() {
needToEat := !ph.isEating && ph.countLeft > 0
if !needToEat {
return
}
canEat := ph.host.wantToEat(ph)
if canEat {
ph.leftCP.Lock()
ph.rightCP.Lock()
fmt.Println("starting to eat", ph.number)
ph.isEating = true
ph.countLeft--
// time.Sleep(100)
// you can uncomment the line above to make sure
// other philos can start or finish eating at this point
ph.host.endEat(ph.number)
ph.isEating = false
fmt.Println("finishing eating", ph.number)
ph.leftCP.Unlock()
ph.rightCP.Unlock()
}
}
func (ph *philo) eat(wg *sync.WaitGroup) {
for ph.countLeft != 0 {
ph.tryToEat()
}
wg.Done()
}
func main() {
h := &host{make([]int, 0), sync.Mutex{}}
chopSticks := make([]*chopStick, 5)
for i := 0; i < 5; i++ {
chopSticks[i] = &chopStick{}
}
philos := make([]*philo, 5)
for i := 1; i < 6; i++ {
ph := &philo{
host: h,
number: i,
leftCP: chopSticks[(i-1)%5],
rightCP: chopSticks[(i)%5],
countLeft: 3,
isEating: false,
}
philos[i-1] = ph
}
wg := &sync.WaitGroup{}
wg.Add(5)
for i := 0; i < 5; i++ {
go philos[i].eat(wg)
}
wg.Wait()
}