1 /* 2 Copyright 2012 Google Inc. 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 provides a duplicate function call suppression 18 // mechanism. 19 package singleflight 20 21 import "sync" 22 23 // call is an in-flight or completed Do call 24 type call struct { 25 wg sync.WaitGroup 26 val interface{} 27 err error 28 } 29 30 // Group represents a class of work and forms a namespace in which 31 // units of work can be executed with duplicate suppression. 32 type Group struct { 33 mu sync.Mutex // protects m 34 m map[string]*call // lazily initialized 35 } 36 37 // Do executes and returns the results of the given function, making 38 // sure that only one execution is in-flight for a given key at a 39 // time. If a duplicate comes in, the duplicate caller waits for the 40 // original to complete and receives the same results. 41 func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, error) { 42 g.mu.Lock() 43 if g.m == nil { 44 g.m = make(map[string]*call) 45 } 46 if c, ok := g.m[key]; ok { 47 g.mu.Unlock() 48 c.wg.Wait() 49 return c.val, c.err 50 } 51 c := new(call) 52 c.wg.Add(1) 53 g.m[key] = c 54 g.mu.Unlock() 55 56 c.val, c.err = fn() 57 c.wg.Done() 58 59 g.mu.Lock() 60 delete(g.m, key) 61 g.mu.Unlock() 62 63 return c.val, c.err 64 } 65