-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
103 lines (88 loc) · 1.92 KB
/
main.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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"sync"
"time"
)
var inputJson = `{
"gophers": [{
"name": "A",
"sleep": 1,
"eat": 1
},
{
"name": "B",
"sleep": 4,
"eat": 3
},
{
"name": "C",
"sleep": 1,
"eat": 4
},
{
"name": "D",
"sleep": 5,
"eat": 2
},
{
"name": "E",
"sleep": 2,
"eat": 3
}
],
"totalFood": 30
}`
type Farm struct {
Gophers []Gopher `json:"gophers"`
TotalFood int `json:"totalFood"`
sync.Mutex
}
func (f *Farm) eatFood(gopher *Gopher) error {
f.Lock()
defer f.Unlock()
if f.TotalFood < gopher.Eat {
log.Printf("gopher %s wants to eat %v food unit(s) but there's not enough food!", gopher.Name, gopher.Eat)
return errors.New("there's not enough food")
}
f.TotalFood -= gopher.Eat
log.Printf("gopher %s eats %v food unit(s). %v food unit(s) left.", gopher.Name, gopher.Eat, f.TotalFood)
return nil
}
type Gopher struct {
Name string `json:"name"`
Sleep time.Duration `json:"sleep"`
Eat int `json:"eat"`
}
func (gopher *Gopher) gopherLive(farm *Farm, messages chan string) {
for {
time.Sleep(time.Second * gopher.Sleep)
if err := farm.eatFood(gopher); err != nil {
messages <- fmt.Sprintf("gopher %s dies. So said!", gopher.Name)
return
}
}
}
func main() {
gopherFarm := &Farm{}
if err := json.Unmarshal([]byte(inputJson), &gopherFarm); err != nil {
log.Fatal("cannot unmarshal: ", err)
}
messages := make(chan string)
for i, gopher := range gopherFarm.Gophers {
log.Printf("gopher %s joins the farm!", gopher.Name)
go gopherFarm.Gophers[i].gopherLive(gopherFarm, messages)
}
log.Println("waiting")
for range gopherFarm.Gophers {
msg, ok := <-messages
if !ok {
log.Fatal("channel was closed")
}
log.Println(msg)
}
log.Println("done waiting")
}