-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdining_philosophers.go
51 lines (43 loc) · 957 Bytes
/
dining_philosophers.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
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
)
type ChopStick struct{ sync.Mutex }
type Philo struct {
leftCS, rightCS *ChopStick
}
func (p Philo) eat() {
for {
p.leftCS.Lock()
p.rightCS.Lock()
fmt.Println("eating")
p.rightCS.Unlock()
p.leftCS.Unlock()
}
}
func main() {
// initialize chopsticks
ChopSticks := make([]*ChopStick, 5)
for i := 0; i < 5; i++ {
ChopSticks[i] = new(ChopStick)
}
// initialize philosophers
philos := make([]*Philo, 5)
for i := 0; i < 5; i++ {
philos[i] = &Philo{ChopSticks[i], ChopSticks[(i+1)%5]}
}
// start the dining
for i := 0; i < 5; i++ {
go philos[i].eat()
}
// this probably would not work, cause main routine would be killed faster...
// so we let it run until user cancels that main routine
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
sig := <-shutdown
fmt.Printf("Shutting down on signal %s..\n", sig)
}