美文网首页
Golang pipline的最佳实践--使用channel

Golang pipline的最佳实践--使用channel

作者: FredricZhu | 来源:发表于2019-06-16 21:13 被阅读0次
package main

import (
    "fmt"
)

func main() {
    generator := func(done <-chan interface{},
        args ...int) <-chan int {
        results := make(chan int)
        go func() {
            defer close(results)
            for _, v := range args {
                select {
                case <-done:
                    return
                case results <- v:
                }
            }
        }()
        return results
    }

    multiply := func(done <-chan interface{},
        intStream <-chan int,
        multiplier int) <-chan int {
        results := make(chan int)
        go func() {
            defer close(results)
            for i := range intStream {
                select {
                case <-done:
                    return
                case results <- i * multiplier:
                }
            }
        }()
        return results
    }

    add := func(done <-chan interface{},
        intStream <-chan int,
        additive int) <-chan int {
        results := make(chan int)
        go func() {
            defer close(results)
            for i := range intStream {
                select {
                case <-done:
                    return
                case results <- i + additive:
                }
            }
        }()
        return results
    }

    done := make(chan interface{})
    defer close(done)

    for v := range multiply(done, add(done, multiply(done, generator(done, 1, 2, 3, 4), 2), 1), 2) {
        fmt.Println(v)
    }
}

程序输出如下,


image.png

相关文章

网友评论

      本文标题:Golang pipline的最佳实践--使用channel

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