美文网首页
Golang Merge多个channel的response到一

Golang Merge多个channel的response到一

作者: FredricZhu | 来源:发表于2019-06-14 17:11 被阅读0次
    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都退出的功能。


    image.png

    相关文章

      网友评论

          本文标题:Golang Merge多个channel的response到一

          本文链接:https://www.haomeiwen.com/subject/qaayfctx.html