-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
example_test.go
67 lines (52 loc) · 1.09 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
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 bool) {
defer wg.Done()
fmt.Println("s1", v)
})
_ = bus.Subscribe("topic", func(v bool) {
defer wg.Done()
fmt.Println("s2", v)
})
// 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)
for i := 0; i < subscribersAmount; i++ {
_ = bus.Subscribe("topic", func(i int, out chan<- int) { out <- i })
}
go func() {
for n := 0; n < queueSize; n++ {
bus.Publish("topic", n, ch)
}
}()
var sum = 0
for sum < (subscribersAmount * queueSize) {
select {
case <-ch:
sum++
}
}
fmt.Println(sum)
// Output:
// 6
}