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.
5 // Package singleflight provides a duplicate function call suppression
7 package singleflight // import "golang.org/x/sync/singleflight"
18 // errGoexit indicates the runtime.Goexit was called in
19 // the user given function.
20 var errGoexit = errors.New("runtime.Goexit was called")
22 // A panicError is an arbitrary value recovered from a panic
23 // with the stack trace during the execution of given function.
24 type panicError struct {
29 // Error implements error interface.
30 func (p *panicError) Error() string {
31 return fmt.Sprintf("%v\n\n%s", p.value, p.stack)
34 func newPanicError(v interface{}) error {
35 stack := debug.Stack()
37 // The first line of the stack trace is of the form "goroutine N [status]:"
38 // but by the time the panic reaches Do the goroutine may no longer exist
39 // and its status will have changed. Trim out the misleading line.
40 if line := bytes.IndexByte(stack[:], '\n'); line >= 0 {
41 stack = stack[line+1:]
43 return &panicError{value: v, stack: stack}
46 // call is an in-flight or completed singleflight.Do call
50 // These fields are written once before the WaitGroup is done
51 // and are only read after the WaitGroup is done.
55 // forgotten indicates whether Forget was called with this call's key
56 // while the call was still in flight.
59 // These fields are read and written with the singleflight
60 // mutex held before the WaitGroup is done, and are read but
61 // not written after the WaitGroup is done.
66 // Group represents a class of work and forms a namespace in
67 // which units of work can be executed with duplicate suppression.
69 mu sync.Mutex // protects m
70 m map[string]*call // lazily initialized
73 // Result holds the results of Do, so they can be passed
81 // Do executes and returns the results of the given function, making
82 // sure that only one execution is in-flight for a given key at a
83 // time. If a duplicate comes in, the duplicate caller waits for the
84 // original to complete and receives the same results.
85 // The return value shared indicates whether v was given to multiple callers.
86 func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
89 g.m = make(map[string]*call)
91 if c, ok := g.m[key]; ok {
96 if e, ok := c.err.(*panicError); ok {
98 } else if c.err == errGoexit {
101 return c.val, c.err, true
109 return c.val, c.err, c.dups > 0
112 // DoChan is like Do but returns a channel that will receive the
113 // results when they are ready.
115 // The returned channel will not be closed.
116 func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result {
117 ch := make(chan Result, 1)
120 g.m = make(map[string]*call)
122 if c, ok := g.m[key]; ok {
124 c.chans = append(c.chans, ch)
128 c := &call{chans: []chan<- Result{ch}}
133 go g.doCall(c, key, fn)
138 // doCall handles the single call for a key.
139 func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
140 normalReturn := false
143 // use double-defer to distinguish panic from runtime.Goexit,
144 // more details see https://golang.org/cl/134395
146 // the given function invoked runtime.Goexit
147 if !normalReturn && !recovered {
158 if e, ok := c.err.(*panicError); ok {
159 // In order to prevent the waiting channels from being blocked forever,
160 // needs to ensure that this panic cannot be recovered.
161 if len(c.chans) > 0 {
163 select {} // Keep this goroutine around so that it will appear in the crash dump.
167 } else if c.err == errGoexit {
168 // Already in the process of goexit, no need to call again
171 for _, ch := range c.chans {
172 ch <- Result{c.val, c.err, c.dups > 0}
180 // Ideally, we would wait to take a stack trace until we've determined
181 // whether this is a panic or a runtime.Goexit.
183 // Unfortunately, the only way we can distinguish the two is to see
184 // whether the recover stopped the goroutine from terminating, and by
185 // the time we know that, the part of the stack trace relevant to the
186 // panic has been discarded.
187 if r := recover(); r != nil {
188 c.err = newPanicError(r)
202 // Forget tells the singleflight to forget about a key. Future calls
203 // to Do for this key will call the function rather than waiting for
204 // an earlier call to complete.
205 func (g *Group) Forget(key string) {
207 if c, ok := g.m[key]; ok {