forked from openshift/origin
/
singleinflight.go
54 lines (44 loc) · 923 Bytes
/
singleinflight.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright (c) 2013 Erik St. Martin, Brian Ketelsen. All rights reserved.
// Use of this source code is governed by The MIT License (MIT) that can be
// found in the LICENSE file.
package server
import (
"sync"
"github.com/miekg/dns"
)
var (
inflight = new(single)
)
// Adapted from singleinflight.go from the original Go Code. Copyright 2013 The Go Authors.
type call struct {
wg sync.WaitGroup
val *dns.RRSIG
err error
dups int
}
type single struct {
sync.Mutex
m map[string]*call
}
func (g *single) Do(key string, fn func() (*dns.RRSIG, error)) (*dns.RRSIG, error, bool) {
g.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
g.Unlock()
c.wg.Wait()
return c.val, c.err, true
}
c := new(call)
c.wg.Add(1)
g.m[key] = c
g.Unlock()
c.val, c.err = fn()
c.wg.Done()
g.Lock()
delete(g.m, key)
g.Unlock()
return c.val, c.err, c.dups > 0
}