-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathcond.go
62 lines (48 loc) · 932 Bytes
/
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
package common
import (
"context"
"sync"
)
////////////////////////////////////////////////////////////////////////////////
type Cond struct {
cond *sync.Cond
}
func NewCond(l sync.Locker) Cond {
return Cond{
cond: sync.NewCond(l),
}
}
func (c *Cond) Signal() {
c.cond.Signal()
}
func (c *Cond) Broadcast() {
c.cond.Broadcast()
}
// Waits for internal condvar event or for ctx cancellation.
func (c *Cond) Wait(ctx context.Context) error {
waitFinishedCtx, waitFinished := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-ctx.Done():
c.cond.Broadcast()
case <-waitFinishedCtx.Done():
return
}
for {
select {
case <-waitFinishedCtx.Done():
return
default:
}
// Signal until c.cond.Wait() has finished for sure.
c.cond.Signal()
}
}()
c.cond.Wait()
waitFinished()
wg.Wait()
return ctx.Err()
}