forked from kamilsk/semaphore
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchannel.go
71 lines (66 loc) · 1.66 KB
/
channel.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
package semaphore
import (
"os"
"os/signal"
"reflect"
"time"
)
// Multiplex combines multiple empty struct channels into one.
// TODO can be leaky, https://github.com/kamilsk/semaphore/issues/133
func Multiplex(channels ...<-chan struct{}) <-chan struct{} {
ch := make(chan struct{})
if len(channels) == 0 {
close(ch)
return ch
}
go func() {
cases := make([]reflect.SelectCase, 0, len(channels))
for _, ch := range channels {
cases = append(cases, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)})
}
reflect.Select(cases)
close(ch)
}()
return ch
}
// WithDeadline returns empty struct channel above on `time.Timer` channel.
// TODO can be leaky, https://github.com/kamilsk/semaphore/issues/133
func WithDeadline(deadline time.Time) <-chan struct{} {
ch := make(chan struct{})
if time.Now().After(deadline) {
close(ch)
return ch
}
go func() {
<-time.After(deadline.Sub(time.Now())) // nolint: gosimple
close(ch)
}()
return ch
}
// WithSignal returns empty struct channel above on `os.Signal` channel.
// TODO can be leaky, https://github.com/kamilsk/semaphore/issues/133
func WithSignal(s os.Signal) <-chan struct{} {
ch := make(chan struct{})
if s == nil {
close(ch)
return ch
}
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, s)
<-c
close(ch)
signal.Stop(c)
}()
return ch
}
// WithTimeout returns empty struct channel above on `time.Timer` channel.
// TODO can be leaky, https://github.com/kamilsk/semaphore/issues/133
func WithTimeout(timeout time.Duration) <-chan struct{} {
ch := make(chan struct{})
if timeout <= 0 {
close(ch)
return ch
}
return WithDeadline(time.Now().Add(timeout))
}