Skip to content

Commit

Permalink
singleflight: Add an example
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kevinburke committed May 13, 2018
1 parent 24b0969 commit 91138e8
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions singleflight/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright 2018 The Go Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package singleflight_test

import (
"fmt"
"log"
"strconv"
"time"

"github.com/golang/groupcache/singleflight"
)

var counter int32
var group singleflight.Group

func Example() {
// No matter how many goroutines call Do, only one call per key will be in
// progress at any time. Callers that share a key will get the same results
// as an in-flight call with that key.
n := int32(41)
v, err := group.Do(strconv.FormatInt(int64(n), 10), func() (interface{}, error) {
time.Sleep(time.Millisecond) // simulate time-consuming action
return n + 1, nil
})
if err != nil {
log.Fatal(err)
}
fmt.Println(v.(int32))
// Output: 42
}

0 comments on commit 91138e8

Please sign in to comment.