Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. package singleflight
  2.  
  3. import "sync"
  4.  
  5. type Group struct {
  6. m map[string]*Result
  7. mu sync.Mutex
  8. }
  9.  
  10. func (g *Group) Do(key string, fn func() (interface{}, error)) *Result {
  11. g.mu.Lock()
  12. defer g.mu.Unlock()
  13. if g.m == nil {
  14. g.m = make(map[string]*Result)
  15. }
  16. if r, ok := g.m[key]; ok {
  17. return r
  18. }
  19. rdy := make(chan struct{})
  20. r := &Result{rdy: rdy}
  21. go func() {
  22. r.val, r.err = fn()
  23. close(rdy)
  24. }()
  25. g.m[key] = r
  26. return r
  27. }
  28.  
  29. func (g *Group) Forget(key string) {
  30. g.mu.Lock()
  31. if g.m != nil {
  32. delete(g.m, key)
  33. }
  34. g.mu.Unlock()
  35. }
  36.  
  37. type Result struct {
  38. rdy <-chan struct{}
  39. val interface{}
  40. err error
  41. }
  42.  
  43. func (r *Result) Done() <-chan struct{} {
  44. return r.rdy
  45. }
  46.  
  47. func (r *Result) Get() (interface{}, error) {
  48. <-r.rdy
  49. return r.val, r.err
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement