forked from cockroachdb/cockroach
/
stopper.go
71 lines (63 loc) · 2.06 KB
/
stopper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)
package util
import "sync"
// A Stopper provides a channel-based mechanism to stop a running
// goroutine. Stopping occurs in two phases: the first is the request
// to stop. The second is the confirmation by the goroutine that it
// has stopped. Multiple goroutines can be stopped using the same
// Stopper instance.
type Stopper struct {
stopper chan struct{}
wg sync.WaitGroup
}
// NewStopper returns an instance of Stopper. Count specifies how
// many goroutines this stopper will stop.
func NewStopper(count int) *Stopper {
s := &Stopper{
stopper: make(chan struct{}),
}
s.Add(count)
return s
}
// Add a new goroutine to the stopper.
func (s *Stopper) Add(count int) {
s.wg.Add(count)
}
// Stop signals the waiting goroutine to stop and then waits
// for it to confirm it has stopped (it does this by calling
// SetStopped).
func (s *Stopper) Stop() {
close(s.stopper)
s.wg.Wait()
}
// ShouldStop returns a channel which will be closed when Stop() has
// been invoked. SetStopped() should be called to confirm.
func (s *Stopper) ShouldStop() <-chan struct{} {
if s == nil {
// A nil stopper will never signal ShouldStop, but will also never panic.
return nil
}
return s.stopper
}
// SetStopped should be called after the ShouldStop() channel has
// been closed to confirm the goroutine has stopped.
func (s *Stopper) SetStopped() {
if s != nil {
s.wg.Done()
}
}