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 dontDeleteForTesting bool // this is only to be used by TestConcurrentExchanges 28} 29 30// Do executes and returns the results of the given function, making 31// sure that only one execution is in-flight for a given key at a 32// time. If a duplicate comes in, the duplicate caller waits for the 33// original to complete and receives the same results. 34// The return value shared indicates whether v was given to multiple callers. 35func (g *singleflight) Do(key string, fn func() (*Msg, time.Duration, error)) (v *Msg, rtt time.Duration, err error, shared bool) { 36 g.Lock() 37 if g.m == nil { 38 g.m = make(map[string]*call) 39 } 40 if c, ok := g.m[key]; ok { 41 c.dups++ 42 g.Unlock() 43 c.wg.Wait() 44 return c.val, c.rtt, c.err, true 45 } 46 c := new(call) 47 c.wg.Add(1) 48 g.m[key] = c 49 g.Unlock() 50 51 c.val, c.rtt, c.err = fn() 52 c.wg.Done() 53 54 if !g.dontDeleteForTesting { 55 g.Lock() 56 delete(g.m, key) 57 g.Unlock() 58 } 59 60 return c.val, c.rtt, c.err, c.dups > 0 61} 62