-
Notifications
You must be signed in to change notification settings - Fork 0
/
diningPhilosophers.go
124 lines (107 loc) · 2.06 KB
/
diningPhilosophers.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
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
package main
import (
"fmt"
"sync"
)
const maxEat = 3
const maxPermissions = 5 * maxEat
const maxSimultaneousEat = 2
var permissionMutex sync.Mutex
type chopStick struct {
sync.Mutex
}
type philosopher struct {
left *chopStick
right *chopStick
id int
}
func (p *philosopher) eat() {
fmt.Printf("starting to eat %d\n", p.id+1)
fmt.Printf("finishing eating %d\n", p.id+1)
}
func (p *philosopher) askPermission(c chan int, per chan bool) {
c <- p.id
per <- true
}
func (p *philosopher) done(d chan bool) {
d <- true
}
func (p *philosopher) Lock() {
p.left.Lock()
p.right.Lock()
}
func (p *philosopher) Unlock() {
p.left.Unlock()
p.right.Unlock()
}
func (p *philosopher) run(c chan int, per chan bool, done chan bool, wg *sync.WaitGroup) {
var i int
for {
permissionMutex.Lock()
p.askPermission(c, per)
status := <-per
<-c
if status {
p.Lock()
permissionMutex.Unlock()
p.eat()
i++
p.Unlock()
p.done(done)
} else {
permissionMutex.Unlock()
}
if i == maxEat {
fmt.Println("\nPhilosopher : ", p.id+1, " done \n")
break
}
}
wg.Done()
}
func host(c chan int, per chan bool, d chan bool) {
var permissionTable = make([]int, 5, 5)
var currentPGranted int
var totalPGranted int
for i := 0; i < maxPermissions; i++ {
status := <-per
id := <-c
if status && (currentPGranted < maxSimultaneousEat) && (permissionTable[id] < maxEat) {
permissionTable[id]++
currentPGranted++
totalPGranted++
per <- true
c <- id
} else {
per <- false
c <- id
}
var done bool
select {
case done = <-d:
if done {
currentPGranted--
}
default:
}
}
}
func main() {
var wg sync.WaitGroup
var cstics = make([]*chopStick, 5, 5)
var philo = make([]*philosopher, 5, 5)
for i := 0; i < 5; i++ {
cstics[i] = new(chopStick)
}
for i := 0; i < 5; i++ {
philo[i] = &philosopher{cstics[i], cstics[(i+1)%5], i}
}
var per = make(chan bool, 100)
var c = make(chan int, 100)
var d = make(chan bool, 100)
wg.Add(5)
go host(c, per, d)
for i := 0; i < 5; i++ {
go philo[i].run(c, per, d, &wg)
}
wg.Wait()
}