-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleflight_example_test.go
More file actions
63 lines (52 loc) · 1.19 KB
/
Copy pathsingleflight_example_test.go
File metadata and controls
63 lines (52 loc) · 1.19 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
package unusual_generics_test
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/xakep666/unusual_generics"
)
func ExampleSingleFlightGroup() {
const (
concurrency = 5
wait = 2 * time.Second
)
var (
wgProduce, wgConsume sync.WaitGroup
sfg unusual_generics.SingleFlightGroup[string]
)
var (
calls int32
results = make(chan unusual_generics.SingleFlightResult[string])
)
wgConsume.Add(1)
go func() {
defer wgConsume.Done()
for result := range results {
fmt.Printf("Val: %q, Shared: %t, Error: %v\n", result.Val, result.Shared, result.Err)
}
}()
for i := 0; i < concurrency; i++ {
wgProduce.Add(1)
go func() {
defer wgProduce.Done()
results <- <-sfg.DoChan("key", func() (string, error) {
// do something heavy
time.Sleep(wait)
atomic.AddInt32(&calls, 1)
return "test", nil
})
}()
}
wgProduce.Wait()
close(results)
wgConsume.Wait()
fmt.Println("Calls:", calls)
// Output:
// Val: "test", Shared: true, Error: <nil>
// Val: "test", Shared: true, Error: <nil>
// Val: "test", Shared: true, Error: <nil>
// Val: "test", Shared: true, Error: <nil>
// Val: "test", Shared: true, Error: <nil>
// Calls: 1
}