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 (
"flag"
"fmt"
"sync"
"time"
)
type Ball struct{ hits int }
func main() {
numSecs := flag.Int("s", 1, "Number of seconds game should last")
flag.Parse()
game(*numSecs)
}
func game(numSecs int) {
var wg sync.WaitGroup
done := make(chan struct{})
p0 := make(chan Ball)
p1 := player(1, &wg, done, p0)
p2 := player(2, &wg, done, p1)
t := time.Tick(time.Duration(numSecs) * time.Second)
p0 <- Ball{}
loop:
for b := range p2 {
select {
case p0 <- b:
case <-t:
break loop
}
}
close(p0)
wg.Wait()
fmt.Println("Done for now")
}
func player(id int, wg *sync.WaitGroup, done <-chan struct{}, input <-chan Ball) <-chan Ball {
out := make(chan Ball)
wg.Go(func() {
defer func() {
close(out)
fmt.Printf("(%d) finished\n", id)
}()
fmt.Printf("(%d) started\n", id)
loop:
for b := range input {
b.hits++
fmt.Printf("(%d) %d\n", id, b.hits)
time.Sleep(100 * time.Millisecond)
select {
case out <- b:
case <-done:
break loop
}
}
})
return out
}
|