forked from vitelabs/go-vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcondTimer.go
58 lines (50 loc) · 943 Bytes
/
condTimer.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
package common
import (
"sync"
"sync/atomic"
"time"
)
type CondTimer struct {
cd *sync.Cond
notifyNum uint32
closed chan struct{}
}
func NewCondTimer() *CondTimer {
mutex := &sync.Mutex{}
return &CondTimer{cd: sync.NewCond(mutex), closed: make(chan struct{})}
}
func (self *CondTimer) Wait() {
old := atomic.SwapUint32(&self.notifyNum, 0)
if old > 0 {
return
}
self.cd.L.Lock()
defer self.cd.L.Unlock()
self.cd.Wait()
}
func (self *CondTimer) Broadcast() {
atomic.AddUint32(&self.notifyNum, 1)
self.cd.Broadcast()
}
func (self *CondTimer) Signal() {
atomic.AddUint32(&self.notifyNum, 1)
self.cd.Signal()
}
func (self *CondTimer) Start(t time.Duration) {
go func() {
ticker := time.NewTicker(t)
defer ticker.Stop()
for {
select {
case <-self.closed:
return
case <-ticker.C:
self.cd.Broadcast()
}
}
}()
}
func (self *CondTimer) Stop() {
close(self.closed)
self.Broadcast()
}