github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/src/pkg/net/singleflight.go (about)

     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  package net
     6  
     7  import "sync"
     8  
     9  // call is an in-flight or completed singleflight.Do call
    10  type call struct {
    11  	wg   sync.WaitGroup
    12  	val  interface{}
    13  	err  error
    14  	dups int
    15  }
    16  
    17  // singleflight represents a class of work and forms a namespace in
    18  // which units of work can be executed with duplicate suppression.
    19  type singleflight struct {
    20  	mu sync.Mutex       // protects m
    21  	m  map[string]*call // lazily initialized
    22  }
    23  
    24  // Do executes and returns the results of the given function, making
    25  // sure that only one execution is in-flight for a given key at a
    26  // time. If a duplicate comes in, the duplicate caller waits for the
    27  // original to complete and receives the same results.
    28  // The return value shared indicates whether v was given to multiple callers.
    29  func (g *singleflight) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
    30  	g.mu.Lock()
    31  	if g.m == nil {
    32  		g.m = make(map[string]*call)
    33  	}
    34  	if c, ok := g.m[key]; ok {
    35  		c.dups++
    36  		g.mu.Unlock()
    37  		c.wg.Wait()
    38  		return c.val, c.err, true
    39  	}
    40  	c := new(call)
    41  	c.wg.Add(1)
    42  	g.m[key] = c
    43  	g.mu.Unlock()
    44  
    45  	c.val, c.err = fn()
    46  	c.wg.Done()
    47  
    48  	g.mu.Lock()
    49  	delete(g.m, key)
    50  	g.mu.Unlock()
    51  
    52  	return c.val, c.err, c.dups > 0
    53  }