http urls monitor.

singleflight.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Copyright 2013 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package singleflight provides a duplicate function call suppression
  14. // mechanism.
  15. package singleflight
  16. import "sync"
  17. // call is an in-flight or completed Do call
  18. type call struct {
  19. wg sync.WaitGroup
  20. val interface{}
  21. err error
  22. }
  23. // Group represents a class of work and forms a namespace in which
  24. // units of work can be executed with duplicate suppression.
  25. type Group struct {
  26. mu sync.Mutex // protects m
  27. m map[string]*call // lazily initialized
  28. }
  29. // Do executes and returns the results of the given function, making
  30. // sure that only one execution is in-flight for a given key at a
  31. // time. If a duplicate comes in, the duplicate caller waits for the
  32. // original to complete and receives the same results.
  33. func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, error) {
  34. g.mu.Lock()
  35. if g.m == nil {
  36. g.m = make(map[string]*call)
  37. }
  38. if c, ok := g.m[key]; ok {
  39. g.mu.Unlock()
  40. c.wg.Wait()
  41. return c.val, c.err
  42. }
  43. c := new(call)
  44. c.wg.Add(1)
  45. g.m[key] = c
  46. g.mu.Unlock()
  47. c.val, c.err = fn()
  48. c.wg.Done()
  49. g.mu.Lock()
  50. delete(g.m, key)
  51. g.mu.Unlock()
  52. return c.val, c.err
  53. }