-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
83 lines (64 loc) · 1.08 KB
/
main.go
File metadata and controls
83 lines (64 loc) · 1.08 KB
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
package main
import (
"fmt"
"sync"
"github.com/benburkert/pubsub"
)
type foo struct {
N int
}
type fooChan chan foo
func (ch fooChan) PublishTo(ctx *pubsub.Context) error {
go func() {
defer ctx.Close()
for {
select {
case v, ok := <-ch:
if !ok {
return
}
ctx.Buffer.Write(v)
case <-ctx.Done:
return
}
}
}()
return nil
}
func (ch fooChan) SubscribeTo(ctx *pubsub.Context) error {
rfn := func(v interface{}) bool {
if v == ctx.Done {
close(ch)
ctx.Close()
return false
}
ch <- v.(foo)
return true
}
ctx.Buffer.ReadTo(rfn)
return nil
}
func main() {
ps, _ := pubsub.New(16, 4)
pch := make(fooChan)
if err := ps.AddPublisher(pch); err != nil {
panic(err)
}
wg := &sync.WaitGroup{}
wg.Add(4)
for _, id := range []string{"A", "B", "C", "D"} {
ch := make(fooChan, 4)
ps.AddSubscriber(ch)
go func(ch <-chan foo, id string) {
defer wg.Done()
for v := range ch {
fmt.Printf("%s got foo.N=%d\n", id, v.N)
}
}(ch, id)
}
for i := 0; i <= 25; i++ {
pch <- foo{N: i}
}
ps.Close()
wg.Wait()
}