Go:一个生产者多个消费者

时间:2023-04-24

浏览:272

作者:佚名

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《Go:一个生产者多个消费者》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

所以我看到了很多在 Go 中实现一个消费者和多个生产者的方法——Go 中的Concurrency 中的经典 fanIn 函数。

我想要的是一个扇出功能。它将一个通道作为参数,它从中读取一个值,并返回一个通道切片,它将这个值的副本写入该通道。

是否有正确/推荐的实施方式?

正确答案

您几乎描述了最好的方法,但这里有一个小的代码示例。

去游乐场: https: //play.golang.org/p/jwdtDXVHJk

package main

import (
    "fmt"
    "time"
)

func producer(iters int) <-chan int {
    c := make(chan int)
    go func() {
        for i := 0; i < iters; i++ {
            c <- i
            time.Sleep(1 * time.Second)
        }
        close(c)
    }()
    return c
}

func consumer(cin <-chan int) {
    for i := range cin {
        fmt.Println(i)
    }
}

func fanOut(ch <-chan int, size, lag int) []chan int {
    cs := make([]chan int, size)
    for i, _ := range cs {
        // The size of the channels buffer controls how far behind the recievers
        // of the fanOut channels can lag the other channels.
        cs[i] = make(chan int, lag)
    }
    go func() {
        for i := range ch {
            for _, c := range cs {
                c <- i
            }
        }
        for _, c := range cs {
            // close all our fanOut channels when the input channel is exhausted.
            close(c)
        }
    }()
    return cs
}

func fanOutUnbuffered(ch <-chan int, size int) []chan int {
    cs := make([]chan int, size)
    for i, _ := range cs {
        // The size of the channels buffer controls how far behind the recievers
        // of the fanOut channels can lag the other channels.
        cs[i] = make(chan int)
    }
    go func() {
        for i := range ch {
            for _, c := range cs {
                c <- i
            }
        }
        for _, c := range cs {
            // close all our fanOut channels when the input channel is exhausted.
            close(c)
        }
    }()
    return cs
}

func main() {
    c := producer(10)
    chans := fanOutUnbuffered(c, 3)
    go consumer(chans[0])
    go consumer(chans[1])
    consumer(chans[2])
}

需要注意的重要部分是,一旦输入通道耗尽,我们如何关闭输出通道。此外,如果其中一个输出通道阻塞发送,它将阻止其他输出通道的发送。我们通过设置通道的缓冲区大小来控制延迟量。

本篇关于《Go:一个生产者多个消费者》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页