Skip to content

Commit 91138e8

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 24b0969 commit 91138e8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

singleflight/example_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Copyright 2018 The Go Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package singleflight_test
18+
19+
import (
20+
"fmt"
21+
"log"
22+
"strconv"
23+
"time"
24+
25+
"github.com/golang/groupcache/singleflight"
26+
)
27+
28+
var counter int32
29+
var group singleflight.Group
30+
31+
func Example() {
32+
// No matter how many goroutines call Do, only one call per key will be in
33+
// progress at any time. Callers that share a key will get the same results
34+
// as an in-flight call with that key.
35+
n := int32(41)
36+
v, err := group.Do(strconv.FormatInt(int64(n), 10), func() (interface{}, error) {
37+
time.Sleep(time.Millisecond) // simulate time-consuming action
38+
return n + 1, nil
39+
})
40+
if err != nil {
41+
log.Fatal(err)
42+
}
43+
fmt.Println(v.(int32))
44+
// Output: 42
45+
}

0 commit comments

Comments
 (0)