美文网首页
Golang桥接模式将多个chan桥接成一个chan

Golang桥接模式将多个chan桥接成一个chan

作者: FredricZhu | 来源:发表于2019-06-18 14:37 被阅读0次

    bridges/bridges.go

    // bridges
    package bridges
    
    type BridgeO struct {
    }
    
    func NewBridge() *BridgeO {
        bridgeO := &BridgeO{}
        return bridgeO
    }
    
    func (bridgeO *BridgeO) OrDone(
        done, c <-chan interface{},
    ) <-chan interface{} {
        valStream := make(chan interface{})
        go func() {
            defer close(valStream)
            for {
                select {
                case <-done:
                    return
                case v, ok := <-c:
                    if ok == false {
                        return
                    }
    
                    select {
                    case valStream <- v:
                    case <-done:
                    }
                }
            }
        }()
        return valStream
    }
    
    func (bridgeO *BridgeO) Bridge(
        done <-chan interface{},
        chanStream <-chan <-chan interface{},
    ) <-chan interface{} {
        valStream := make(chan interface{})
        go func() {
            defer close(valStream)
            for {
                var stream <-chan interface{}
                select {
                case maybeStream, ok := <-chanStream:
                    if ok == false {
                        return
                    }
    
                    stream = maybeStream
                case <-done:
                    return
                }
    
                for val := range bridgeO.OrDone(done, stream) {
                    select {
                    case valStream <- val:
                    case <-done:
                    }
                }
            }
        }()
        return valStream
    }
    

    bridge_demo.go

    // bridgedemo
    package main
    
    import (
        "bridgedemo/bridges"
        "fmt"
    )
    
    func main() {
        bridge := bridges.NewBridge()
        genVals := func() <-chan <-chan interface{} {
            chanStream := make(chan (<-chan interface{}))
            go func() {
                defer close(chanStream)
                for i := 0; i < 10; i++ {
                    stream := make(chan interface{}, 1)
                    stream <- i
                    close(stream)
                    chanStream <- stream
                }
            }()
            return chanStream
        }
    
        done := make(chan interface{})
        defer close(done)
        for v := range bridge.Bridge(done, genVals()) {
            fmt.Printf("%v ", v)
        }
    
        fmt.Println()
    }
    

    程序输出如下,


    image.png

    相关文章

      网友评论

          本文标题:Golang桥接模式将多个chan桥接成一个chan

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