Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.70 KB | None | 0 0
  1. type Batcher struct {
  2.     valueSlow *slow.Value
  3.     value interface{}
  4.     mu sync.Mutex
  5.     con *sync.Cond
  6.     done, running bool
  7. }
  8.  
  9. func (b *Batcher) Load() interface{} {
  10.     b.mu.Lock()
  11.     defer b.mu.Unlock()
  12.  
  13.     if b.done {
  14.         b.done = false
  15.  
  16.         b.mu.Unlock()
  17.         b.value = b.valueSlow.Load()
  18.         b.mu.Lock()
  19.  
  20.         b.con.Broadcast()
  21.         return b.value
  22.     }
  23.  
  24.     if b.running {
  25.         b.con.Wait()
  26.  
  27.         if !b.done {
  28.             b.con.Wait()
  29.             return b.value
  30.         }
  31.     }
  32.     b.running = true
  33.     b.mu.Unlock()
  34.  
  35.     b.value = b.valueSlow.Load()
  36.  
  37.     b.mu.Lock()
  38.     b.done = true
  39.     b.con.Broadcast()
  40.  
  41.     return b.value
  42. }
  43.  
  44. func NewBatcher(v *slow.Value) *Batcher {
  45.     mu := sync.Mutex{}
  46.     return &Batcher{valueSlow: v, mu: mu,  con: sync.NewCond(&mu)}
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement