diff --git a/singleflight/example_test.go b/singleflight/example_test.go new file mode 100644 index 00000000..1817a32a --- /dev/null +++ b/singleflight/example_test.go @@ -0,0 +1,48 @@ +/* +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" + "log" + "sync/atomic" + "time" + + "github.com/golang/groupcache/singleflight" +) + +var counter int32 +var networkGroup 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, err := networkGroup.Do("key", expensiveNetworkCall) + if err != nil { + log.Fatal(err) + } + fmt.Println(v.(int32)) + // Output: 1 +}