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"
11 // call is an in-flight or completed singleflight.Do call
15 // These fields are written once before the WaitGroup is done
16 // and are only read after the WaitGroup is done.
20 // forgotten indicates whether Forget was called with this call's key
21 // while the call was still in flight.
24 // These fields are read and written with the singleflight
25 // mutex held before the WaitGroup is done, and are read but
26 // not written after the WaitGroup is done.
31 // Group represents a class of work and forms a namespace in
32 // which units of work can be executed with duplicate suppression.
34 mu sync.Mutex // protects m
35 m map[string]*call // lazily initialized
38 // Result holds the results of Do, so they can be passed
46 // Do executes and returns the results of the given function, making
47 // sure that only one execution is in-flight for a given key at a
48 // time. If a duplicate comes in, the duplicate caller waits for the
49 // original to complete and receives the same results.
50 // The return value shared indicates whether v was given to multiple callers.
51 func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
54 g.m = make(map[string]*call)
56 if c, ok := g.m[key]; ok {
60 return c.val, c.err, true
68 return c.val, c.err, c.dups > 0
71 // DoChan is like Do but returns a channel that will receive the
72 // results when they are ready.
73 func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result {
74 ch := make(chan Result, 1)
77 g.m = make(map[string]*call)
79 if c, ok := g.m[key]; ok {
81 c.chans = append(c.chans, ch)
85 c := &call{chans: []chan<- Result{ch}}
90 go g.doCall(c, key, fn)
95 // doCall handles the single call for a key.
96 func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
104 for _, ch := range c.chans {
105 ch <- Result{c.val, c.err, c.dups > 0}
110 // Forget tells the singleflight to forget about a key. Future calls
111 // to Do for this key will call the function rather than waiting for
112 // an earlier call to complete.
113 func (g *Group) Forget(key string) {
115 if c, ok := g.m[key]; ok {