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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
package xsync
import (
"context"
"fmt"
"testing"
"time"
"github.com/bradenaw/juniper/xtime"
)
func ExampleLazy() {
var (
expensive = Lazy(func() string {
fmt.Println("doing expensive init")
return "foo"
})
)
fmt.Println(expensive())
fmt.Println(expensive())
// Output:
// doing expensive init
// foo
// foo
}
func TestGroup(t *testing.T) {
g := NewGroup(context.Background())
dos := make(chan struct{}, 100)
g.Do(func(ctx context.Context) {
for {
err := xtime.SleepContext(ctx, 50*time.Millisecond)
if err != nil {
return
}
select {
case dos <- struct{}{}:
default:
}
}
})
periodics := make(chan struct{}, 100)
g.Periodic(35*time.Millisecond, 0 /*jitter*/, func(ctx context.Context) {
select {
case periodics <- struct{}{}:
default:
}
})
periodicOrTriggers := make(chan struct{}, 100)
periodicOrTrigger := g.PeriodicOrTrigger(75*time.Millisecond, 0 /*jitter*/, func(ctx context.Context) {
select {
case periodicOrTriggers <- struct{}{}:
default:
}
})
triggers := make(chan struct{}, 100)
trigger := g.Trigger(func(ctx context.Context) {
select {
case triggers <- struct{}{}:
default:
}
})
trigger()
periodicOrTrigger()
time.Sleep(200 * time.Millisecond)
trigger()
<-dos
<-dos
<-dos
<-dos
<-periodics
<-periodics
<-periodics
<-periodics
<-periodics
<-periodicOrTriggers
<-periodicOrTriggers
<-periodicOrTriggers
<-triggers
<-triggers
g.StopAndWait()
g.Do(func(ctx context.Context) {
panic("this will never spawn because StopAndWait was already called")
})
// Jank, but just in case we'd be safe from the above panic just because the test is over.
time.Sleep(200 * time.Millisecond)
}
|