1// Copyright 2013 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5// Adapted for dns package usage by Miek Gieben. 6 7package dns 8 9import "sync" 10import "time" 11 12// call is an in-flight or completed singleflight.Do call 13type call struct { 14 wg sync.WaitGroup 15 val *Msg 16 rtt time.Duration 17 err error 18 dups int 19} 20 21// singleflight represents a class of work and forms a namespace in 22// which units of work can be executed with duplicate suppression. 23type singleflight struct { 24 sync.Mutex // protects m 25 m map[string]*call // lazily initialized 26} 27 28// Do executes and returns the results of the given function, making 29// sure that only one execution is in-flight for a given key at a 30// time. If a duplicate comes in, the duplicate caller waits for the 31// original to complete and receives the same results. 32// The return value shared indicates whether v was given to multiple callers. 33func (g *singleflight) Do(key string, fn func() (*Msg, time.Duration, error)) (v *Msg, rtt time.Duration, err error, shared bool) { 34 g.Lock() 35 if g.m == nil { 36 g.m = make(map[string]*call) 37 } 38 if c, ok := g.m[key]; ok { 39 c.dups++ 40 g.Unlock() 41 c.wg.Wait() 42 return c.val, c.rtt, c.err, true 43 } 44 c := new(call) 45 c.wg.Add(1) 46 g.m[key] = c 47 g.Unlock() 48 49 c.val, c.rtt, c.err = fn() 50 c.wg.Done() 51 52 g.Lock() 53 delete(g.m, key) 54 g.Unlock() 55 56 return c.val, c.rtt, c.err, c.dups > 0 57} 58