forked from vardius/message-bus
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexample_test.go
74 lines (59 loc) · 1.18 KB
/
example_test.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 messagebus_test
import (
"fmt"
"sync"
messagebus "github.com/vardius/message-bus"
)
func Example() {
queueSize := 100
bus := messagebus.New(queueSize)
var wg sync.WaitGroup
wg.Add(2)
bus.Subscribe("topic", func(v interface{}) {
defer wg.Done()
fmt.Println("s1", v.(bool))
})
bus.Subscribe("topic", func(v interface{}) {
defer wg.Done()
fmt.Println("s2", v.(bool))
})
// Publish block only when the buffer of one of the subscribers is full.
// change the buffer size altering queueSize when creating new messagebus
bus.Publish("topic", true)
wg.Wait()
// Unordered output:
// s1 true
// s2 true
}
func Example_second() {
queueSize := 2
subscribersAmount := 3
ch := make(chan int, queueSize)
defer close(ch)
bus := messagebus.New(queueSize)
type Arg struct {
i int
out chan<- int
}
for i := 0; i < subscribersAmount; i++ {
bus.Subscribe("topic", func(arg interface{}) {
a := arg.(*Arg)
a.out <- a.i
})
}
go func() {
for n := 0; n < queueSize; n++ {
bus.Publish("topic", &Arg{n, ch})
}
}()
var sum = 0
for sum < (subscribersAmount * queueSize) {
select {
case <-ch:
sum++
}
}
fmt.Println(sum)
// Output:
// 6
}