runner.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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 async
  14. import (
  15. "sync"
  16. )
  17. // Runner is an abstraction to make it easy to start and stop groups of things that can be
  18. // described by a single function which waits on a channel close to exit.
  19. type Runner struct {
  20. lock sync.Mutex
  21. loopFuncs []func(stop chan struct{})
  22. stop *chan struct{}
  23. }
  24. // NewRunner makes a runner for the given function(s). The function(s) should loop until
  25. // the channel is closed.
  26. func NewRunner(f ...func(stop chan struct{})) *Runner {
  27. return &Runner{loopFuncs: f}
  28. }
  29. // Start begins running.
  30. func (r *Runner) Start() {
  31. r.lock.Lock()
  32. defer r.lock.Unlock()
  33. if r.stop == nil {
  34. c := make(chan struct{})
  35. r.stop = &c
  36. for i := range r.loopFuncs {
  37. go r.loopFuncs[i](*r.stop)
  38. }
  39. }
  40. }
  41. // Stop stops running.
  42. func (r *Runner) Stop() {
  43. r.lock.Lock()
  44. defer r.lock.Unlock()
  45. if r.stop != nil {
  46. close(*r.stop)
  47. r.stop = nil
  48. }
  49. }