summaryrefslogtreecommitdiff
path: root/philo.go
blob: 0256aeb712192fe26fb7f225536349e3860379d4 (plain)
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
130
131
132
133
134
135
136
137
138
139
package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

const (
	bites = 3
	delay = 3
)

var philo = []string{
	"Aristotle",
	"Kant",
	"Spinoza",
	"Marx",
	"Russell",
}

type Philo struct {
	Name  string
	LHS   chan bool
	RHS   chan bool
	Bites int
}

func rndDelay() {
	n := time.Duration(rand.Intn(delay) + 1)
	time.Sleep(n * time.Second)
}

func (p Philo) state(s string) {
	fmt.Printf("%10s %s\n", p.Name, s)
}

type stateFn func(*Philo) stateFn

func arrive(p *Philo) stateFn {
	p.state("arrives")

	return hungry
}

func hungry(p *Philo) stateFn {
	p.state("is hungry")

	<-p.LHS // grab left fork

	select {
	case <-p.RHS: // try to grab right fork
		return eat
	case <-time.After(time.Second):
		p.LHS <- true // put left fork back
		return starve
	}

	return eat
}

func starve(p *Philo) stateFn {
	p.state("is starving")
	rndDelay()

	return hungry
}

func eat(p *Philo) stateFn {
	p.state("is eating")
	rndDelay()

	p.LHS <- true // release left fork
	p.RHS <- true // release right fork

	if p.Bites -= 1; p.Bites <= 0 {
		return leave
	}

	return think
}

func think(p *Philo) stateFn {
	p.state("is thinking")
	rndDelay()

	return hungry
}

func leave(p *Philo) stateFn {
	p.state("leaves")

	return nil
}

func prepare(n int) []chan bool {
	forks := make([]chan bool, n)

	for i := range forks {
		forks[i] = make(chan bool, 1)
		forks[i] <- true // put a fork
	}

	return forks
}

func init() {
	rand.Seed(time.Now().UnixNano())
}

func main() {
	fmt.Println(len(philo), "philosophers dining")
	defer fmt.Println("Table is empty")

	forks := prepare(len(philo))

	wg := sync.WaitGroup{}
	defer wg.Wait()

	for i, name := range philo {
		wg.Add(1)

		p := &Philo{
			Name:  name,
			LHS:   forks[i],
			RHS:   forks[(i+1)%len(philo)],
			Bites: bites,
		}

		go func(p *Philo) {
			defer wg.Done()

			for state := arrive; state != nil; {
				state = state(p)
			}
		}(p)
	}
}