-
Notifications
You must be signed in to change notification settings - Fork 11
/
cond.go
72 lines (60 loc) · 1.01 KB
/
cond.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
72
package basic
import (
"sync/atomic"
"time"
)
type Cond struct {
notify chan struct{}
countor int32
}
func NewCond(waitor int) *Cond {
return &Cond{notify: make(chan struct{}, waitor)}
}
func (c *Cond) Wait() {
atomic.AddInt32(&c.countor, 1)
defer atomic.AddInt32(&c.countor, -1)
select {
case <-c.notify:
}
}
func (c *Cond) WaitForTimeout(dura time.Duration) bool {
atomic.AddInt32(&c.countor, 1)
defer atomic.AddInt32(&c.countor, -1)
select {
case <-c.notify:
case <-time.Tick(dura):
return true
}
return false
}
func (c *Cond) WaitForTick(ticker *time.Ticker) bool {
atomic.AddInt32(&c.countor, 1)
defer atomic.AddInt32(&c.countor, -1)
select {
case <-c.notify:
case <-ticker.C:
return true
}
return false
}
func (c *Cond) Signal() {
select {
case c.notify <- struct{}{}:
default:
return
}
}
func (c *Cond) Drain() {
for {
select {
case <-c.notify:
default:
return
}
}
}
func (c *Cond) Broadcast() {
for atomic.LoadInt32(&c.countor) > 0 {
c.notify <- struct{}{}
}
}