-
Notifications
You must be signed in to change notification settings - Fork 0
/
dining.go
70 lines (51 loc) · 1005 Bytes
/
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
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type host struct {
eaters chan bool
}
type philosopher struct {
id int
}
type chopstick struct {
}
var chopsticks = make(chan chopstick, 5)
var wg sync.WaitGroup
func (p philosopher) eat(h *host) {
for i := 0; i < 3; i++ {
<-h.eaters
left, right := <-chopsticks, <-chopsticks
fmt.Println("starting to eat: ", p.id)
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
fmt.Println("finished eating: ", p.id)
chopsticks <- right
chopsticks <- left
h.eaters <- true
}
wg.Done()
}
func (h host) begin() {
for i := 0; i < 2; i++ {
h.eaters <- true
}
}
func main() {
rand.Seed(time.Now().UnixNano())
host := new(host)
host.eaters = make(chan bool, 2)
go host.begin()
philosophers := make([]*philosopher, 5)
for i := 0; i < 5; i++ {
philosophers[i] = &philosopher{i + 1}
chopsticks <- *new(chopstick)
}
for i := 0; i < 5; i++ {
wg.Add(1)
go philosophers[i].eat(host)
}
wg.Wait()
}