From f3f96850a8ccad039d61b810d4ae11eeb05a885b Mon Sep 17 00:00:00 2001 From: Kevin Burke Date: Sat, 22 Oct 2016 23:11:56 -0700 Subject: [PATCH] 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. --- singleflight/example_test.go | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 singleflight/example_test.go diff --git a/singleflight/example_test.go b/singleflight/example_test.go new file mode 100644 index 00000000..c31ef6d8 --- /dev/null +++ b/singleflight/example_test.go @@ -0,0 +1,44 @@ +/* +Copyright 2016 Google Inc. + +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" + "sync/atomic" + "time" + + "github.com/golang/groupcache/singleflight" +) + +var counter int32 +var g singleflight.Group + +// expensiveNetworkCall simulates an expensive action. +func expensiveNetworkCall() (interface{}, error) { + time.Sleep(1) + atomic.AddInt32(&counter, 1) + return counter, nil +} + +func Example() { + // No matter how many threads call Do, only one network 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. + v, _ := g.Do("key", expensiveNetworkCall) + fmt.Println(v.(int32)) + // Output: 1 +}