Skip to content

Commit

Permalink
refactor: single flight update.
Browse files Browse the repository at this point in the history
  • Loading branch information
FGadvancer committed Jul 2, 2024
1 parent 4a39d5c commit dc1cdae
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions pkg/localcache/singleflight.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,32 @@ package localcache

import "sync"

type call[K comparable, V any] struct {
type call[V any] struct {
wg sync.WaitGroup
val V
err error
}

type SingleFlight[K comparable, V any] struct {
mu sync.Mutex
m map[K]*call[K, V]
m map[K]*call[V]
}

func NewSingleFlight[K comparable, V any]() *SingleFlight[K, V] {
return &SingleFlight[K, V]{m: make(map[K]*call[K, V])}
return &SingleFlight[K, V]{m: make(map[K]*call[V])}
}

func (r *SingleFlight[K, V]) Do(key K, fn func() (V, error)) (V, error) {
r.mu.Lock()
if r.m == nil {
r.m = make(map[K]*call[K, V])
r.m = make(map[K]*call[V])
}
if c, ok := r.m[key]; ok {
r.mu.Unlock()
c.wg.Wait()
return c.val, c.err
}
c := new(call[K, V])
c := new(call[V])
c.wg.Add(1)
r.m[key] = c
r.mu.Unlock()
Expand Down

0 comments on commit dc1cdae

Please sign in to comment.