package orch
type Orch struct {
}
func New() *Orch {
return &Orch{}
}
func (orch *Orch) Or(channels ...<-chan interface{}) <-chan interface{} {
switch len(channels) {
case 0:
return nil
case 1:
return channels[0]
}
orDone := make(chan interface{})
go func() {
defer close(orDone)
switch len(channels) {
case 2:
select {
case <-channels[0]:
case <-channels[1]:
}
default:
select {
case <-channels[0]:
case <-channels[1]:
case <-channels[2]:
case <-orch.Or(append(channels[3:], orDone)...):
}
}
}()
return orDone
}
package main
import (
"fmt"
"mergechanresponse/orch"
"time"
)
func main() {
sig := func(after time.Duration) <-chan interface{} {
c := make(chan interface{})
go func() {
defer close(c)
time.Sleep(after)
}()
return c
}
och := orch.New()
start := time.Now()
<-och.Or(
sig(2*time.Hour),
sig(5*time.Minute),
sig(1*time.Second),
sig(1*time.Hour),
sig(1*time.Minute),
)
fmt.Printf("done after %v \n", time.Since(start))
}
程序输出如下,实现一个channel退出,所有channel都退出的功能。
有疑问加站长微信联系(非本文作者)