github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/internal/singleflight/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 singleflight provides a duplicate function call suppression
     6  // mechanism.
     7  package singleflight
     8  
     9  import "github.com/shogo82148/std/sync"
    10  
    11  // Group represents a class of work and forms a namespace in
    12  // which units of work can be executed with duplicate suppression.
    13  type Group struct {
    14  	mu sync.Mutex
    15  	m  map[string]*call
    16  }
    17  
    18  // Result holds the results of Do, so they can be passed
    19  // on a channel.
    20  type Result struct {
    21  	Val    any
    22  	Err    error
    23  	Shared bool
    24  }
    25  
    26  // Do executes and returns the results of the given function, making
    27  // sure that only one execution is in-flight for a given key at a
    28  // time. If a duplicate comes in, the duplicate caller waits for the
    29  // original to complete and receives the same results.
    30  // The return value shared indicates whether v was given to multiple callers.
    31  func (g *Group) Do(key string, fn func() (any, error)) (v any, err error, shared bool)
    32  
    33  // DoChan is like Do but returns a channel that will receive the
    34  // results when they are ready.
    35  func (g *Group) DoChan(key string, fn func() (any, error)) <-chan Result
    36  
    37  // ForgetUnshared tells the singleflight to forget about a key if it is not
    38  // shared with any other goroutines. Future calls to Do for a forgotten key
    39  // will call the function rather than waiting for an earlier call to complete.
    40  // Returns whether the key was forgotten or unknown--that is, whether no
    41  // other goroutines are waiting for the result.
    42  func (g *Group) ForgetUnshared(key string) bool