-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
76 lines (63 loc) · 1.17 KB
/
channel.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
package main
import "fmt"
//import "time"
type PersonHandler interface {
Batch(origs <-chan Person) <-chan Person
Handle(orig *Person)
}
type PersonHandlerImpl struct {}
type Person string
func main() {
handler := getPersonHandler()
origs := make(chan Person, 100)
dests := handler.Batch(origs)
fetchPerson(origs)
sign := savePerson(dests)
<-sign
}
func (handler PersonHandlerImpl) Batch(origs <-chan Person) <-chan Person {
dests := make(chan Person, 100)
go func(){
for{
p, ok := <-origs
if !ok {
close(dests)
break
}
handler.Handle(&p)
dests <- p
}
}()
return dests
}
func (handler PersonHandlerImpl) Handle(orig *Person) {
fmt.Printf("%s\n", string(*orig))
}
func getPersonHandler() PersonHandler {
return new(PersonHandlerImpl)
}
func fetchPerson(origs chan<- Person) {
go func(){
for i := 0; i< 100; i++ {
p := new(Person)
*p = Person("person." + string(i))
origs <- *p
}
close(origs)
}()
}
func savePerson(dest <-chan Person) <-chan byte {
sign := make(chan byte)
go func(){
for{
p, ok := <-dest
if !ok {
sign <- 0
close(sign)
break
}
fmt.Printf("save %s\n", string(p))
}
}()
return sign
}