1
0

shutdown.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package shutdown
  15. import (
  16. "sync"
  17. )
  18. type Shutdown struct {
  19. doing bool
  20. ending bool
  21. startCh chan struct{}
  22. doneCh chan struct{}
  23. mu sync.Mutex
  24. }
  25. func New() *Shutdown {
  26. return &Shutdown{
  27. doing: false,
  28. ending: false,
  29. startCh: make(chan struct{}),
  30. doneCh: make(chan struct{}),
  31. }
  32. }
  33. func (s *Shutdown) Start() {
  34. s.mu.Lock()
  35. defer s.mu.Unlock()
  36. if !s.doing {
  37. s.doing = true
  38. close(s.startCh)
  39. }
  40. }
  41. func (s *Shutdown) WaitStart() {
  42. <-s.startCh
  43. }
  44. func (s *Shutdown) Done() {
  45. s.mu.Lock()
  46. defer s.mu.Unlock()
  47. if !s.ending {
  48. s.ending = true
  49. close(s.doneCh)
  50. }
  51. }
  52. func (s *Shutdown) WaitDone() {
  53. <-s.doneCh
  54. }