| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package sumweb |
| 9 |
|
| 10 |
import ( |
| 11 |
"sync" |
| 12 |
"sync/atomic" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
type parCache struct { |
| 17 |
m sync.Map |
| 18 |
} |
| 19 |
|
| 20 |
type cacheEntry struct { |
| 21 |
done uint32 |
| 22 |
mu sync.Mutex |
| 23 |
result interface{} |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
func (c *parCache) Do(key interface{}, f func() interface{}) interface{} { |
| 30 |
entryIface, ok := c.m.Load(key) |
| 31 |
if !ok { |
| 32 |
entryIface, _ = c.m.LoadOrStore(key, new(cacheEntry)) |
| 33 |
} |
| 34 |
e := entryIface.(*cacheEntry) |
| 35 |
if atomic.LoadUint32(&e.done) == 0 { |
| 36 |
e.mu.Lock() |
| 37 |
if atomic.LoadUint32(&e.done) == 0 { |
| 38 |
e.result = f() |
| 39 |
atomic.StoreUint32(&e.done, 1) |
| 40 |
} |
| 41 |
e.mu.Unlock() |
| 42 |
} |
| 43 |
return e.result |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
func (c *parCache) Get(key interface{}) interface{} { |
| 50 |
entryIface, ok := c.m.Load(key) |
| 51 |
if !ok { |
| 52 |
return nil |
| 53 |
} |
| 54 |
e := entryIface.(*cacheEntry) |
| 55 |
if atomic.LoadUint32(&e.done) == 0 { |
| 56 |
return nil |
| 57 |
} |
| 58 |
return e.result |
| 59 |
} |