-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdining-philosophers-waiter.go
58 lines (51 loc) · 1.06 KB
/
dining-philosophers-waiter.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
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var forks [5]bool = [5]bool{false, false, false, false, false} // is the fork being used
var m = sync.Mutex{}
var waiter *sync.Cond = sync.NewCond(&m)
func eat(philosopher int) {
for true {
var left, right = philosopher, (philosopher + 1) % 5
waiter.L.Lock()
if !forks[left] && !forks[right] { // the forks are available
forks[left], forks[right] = true, true //pick them up
waiter.L.Unlock()
break
} else {
waiter.Wait()
waiter.L.Unlock()
}
}
}
func think(philosopher int) {
var left, right = philosopher, (philosopher + 1) % 5
waiter.L.Lock()
forks[left], forks[right] = false, false //put forks down
waiter.L.Unlock()
waiter.Broadcast()
}
func sleep() {
r := rand.Intn(10)
time.Sleep(time.Duration(r) * time.Second)
}
func philosopher(i int) {
for true {
eat(i)
fmt.Printf("Philosopher %d eating\n", i)
sleep()
think(i)
fmt.Printf("Philpsopher %d thinking\n", i)
sleep()
}
}
func main() {
for i := 0; i < 5; i++ {
go philosopher(i)
}
select {} // run forever
}