-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbroadcast_test.go
More file actions
76 lines (65 loc) · 1.42 KB
/
broadcast_test.go
File metadata and controls
76 lines (65 loc) · 1.42 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
package broadcast
import (
"context"
"fmt"
"time"
)
func ExampleBroadcast() {
// b guards currValue
var b Broadcast
var currValue int
go func() {
// 0 to 9 inclusive
for i := range 10 {
<-time.After(time.Millisecond * 20)
b.HoldLock(func(broadcast func(), getWaitCh func() <-chan struct{}) {
currValue = i
broadcast()
})
}
}()
var waitCh <-chan struct{}
var gotValue int
for {
b.HoldLock(func(broadcast func(), getWaitCh func() <-chan struct{}) {
gotValue = currValue
waitCh = getWaitCh()
})
// last value
if gotValue == 9 {
// success
break
}
// otherwise keep waiting
<-waitCh
}
fmt.Printf("waited for value to increment: %v\n", gotValue)
// Output: waited for value to increment: 9
}
func ExampleBroadcast_Wait() {
// b guards currValue
var b Broadcast
var currValue int
go func() {
// 0 to 9 inclusive
for i := range 10 {
<-time.After(time.Millisecond * 20)
b.HoldLock(func(broadcast func(), getWaitCh func() <-chan struct{}) {
currValue = i
broadcast()
})
}
}()
ctx := context.Background()
var gotValue int
err := b.Wait(ctx, func(broadcast func(), getWaitCh func() <-chan struct{}) (bool, error) {
gotValue = currValue
return gotValue == 9, nil
})
if err != nil {
fmt.Printf("failed to wait for value: %v", err.Error())
return
}
fmt.Printf("waited for value to increment: %v\n", gotValue)
// Output: waited for value to increment: 9
}