Skip to content

Commit

Permalink
slim singleflight
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Jan 4, 2024
1 parent f1c76d5 commit 19c96d9
Showing 1 changed file with 0 additions and 43 deletions.
43 changes: 0 additions & 43 deletions singleflight.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,30 +62,6 @@ func (g *singleflight_Group[K, V]) Do(key K, fn func() (V, error)) (v V, err err
return c.val, c.err, c.dups > 0
}

// DoChan is like Do but returns a channel that will receive the
// results when they are ready.
func (g *singleflight_Group[K, V]) DoChan(key K, fn func() (V, error)) <-chan singleflight_Result[V] {
ch := make(chan singleflight_Result[V], 1)
g.mu.Lock()
if g.m == nil {
g.m = make(map[K]*singleflight_call[V])
}
if c, ok := g.m[key]; ok {
c.dups++
c.chans = append(c.chans, ch)
g.mu.Unlock()
return ch
}
c := &singleflight_call[V]{chans: []chan<- singleflight_Result[V]{ch}}
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()

go g.doCall(c, key, fn)

return ch
}

// doCall handles the single singleflight_call for a key.
func (g *singleflight_Group[K, V]) doCall(c *singleflight_call[V], key K, fn func() (V, error)) {
c.val, c.err = fn()
Expand All @@ -98,22 +74,3 @@ func (g *singleflight_Group[K, V]) doCall(c *singleflight_call[V], key K, fn fun
}
g.mu.Unlock()
}

// ForgetUnshared tells the singleflight to forget about a key if it is not
// shared with any other goroutines. Future singleflight_calls to Do for a forgotten key
// will singleflight_call the function rather than waiting for an earlier singleflight_call to complete.
// Returns whether the key was forgotten or unknown--that is, whether no
// other goroutines are waiting for the result.
func (g *singleflight_Group[K, V]) ForgetUnshared(key K) bool {
g.mu.Lock()
defer g.mu.Unlock()
c, ok := g.m[key]
if !ok {
return true
}
if c.dups == 0 {
delete(g.m, key)
return true
}
return false
}

0 comments on commit 19c96d9

Please sign in to comment.