Skip to content

Commit 5ea4293

Browse files
committed
singleflight: Add an example
I was curious about the best way to initialize a Group - it turns out you just do `var g Group` - but figured this package could use a package-level example demonstrating an example use case.
1 parent a6b377e commit 5ea4293

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

singleflight/example_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package singleflight
2+
3+
import (
4+
"fmt"
5+
"sync"
6+
"time"
7+
)
8+
9+
func Example() {
10+
// Spin up 5 goroutines, each of which calls a function that increments
11+
// a counter. At the end, the counter will only increment once and the
12+
// counter value (1) will be returned to all goroutines.
13+
counter := 0
14+
var g Group
15+
var wg sync.WaitGroup
16+
var results [5]int
17+
c := make(chan bool)
18+
for i := 0; i < 5; i++ {
19+
wg.Add(1)
20+
go func(i int) {
21+
ctrval, _ := g.Do("key", func() (interface{}, error) {
22+
counter++
23+
<-c // make sure every goroutine has started before returning
24+
return counter, nil
25+
})
26+
results[i] = ctrval.(int)
27+
wg.Done()
28+
}(i)
29+
}
30+
// Sleep so all of the goroutines start before we send a message on the
31+
// channel
32+
time.Sleep(10 * time.Millisecond)
33+
c <- true
34+
wg.Wait()
35+
fmt.Println(results)
36+
// Output: [1 1 1 1 1]
37+
}

0 commit comments

Comments
 (0)