-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait.go
85 lines (82 loc) · 1.58 KB
/
wait.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
73
74
75
76
77
78
79
80
81
82
83
84
85
package pipe
// Wait waits for the input channel to close and sends a signal to the returned channel.
//
// # Example
//
// <-Wait(input1)
// select {
// case <-Wait(input2):
// case <-Wait(input3):
// }
// // Will executed after input1 closed and input2 or input3 closed
func Wait[T any](in <-chan T) <-chan struct{} {
q := make(chan struct{})
go func() {
for {
if _, ok := <-in; !ok {
break
}
}
q <- struct{}{}
close(q)
}()
return q
}
// WaitAll waits for all input channels to close and sends a signal to the returned channel.
//
// # Example
//
// <-WaitAll(input1, input2)
// // Will executed after input1 AND input2 closed
//
// // It's equal:
// <-Wait(input1)
// <-Wait(input2)
func WaitAll[T any](in ...<-chan T) <-chan struct{} {
q := make(chan struct{})
go func() {
for i := range in {
for {
if _, ok := <-in[i]; !ok {
break
}
}
}
q <- struct{}{}
close(q)
}()
return q
}
// WaitAny waits for one of the input channels to close and sends a signal to the returned channel.
// All other channels are read to the end in the background.
//
// # Example
//
// <-WaitAny(input1, input2)
// // Will executed after input1 OR input2 closed
//
// // It's equal:
// select {
// case <-Wait(input1):
// case <-Wait(input2):
// }
func WaitAny[T any](in ...<-chan T) <-chan struct{} {
q := make(chan struct{})
go func() {
queue := make(chan struct{}, len(in))
for i := range in {
i := i
go func() {
for {
if _, ok := <-in[i]; !ok {
queue <- struct{}{}
break
}
}
}()
}
<-queue
q <- struct{}{}
}()
return q
}