【问题标题】:How do channels distribute evenly to multiple goroutines [duplicate]通道如何均匀分布到多个 goroutines [重复]
【发布时间】:2016-03-25 18:53:17
【问题描述】:

我有这段代码可以在任何给定时间上传最多 30 个文件(可能需要上传数千个文件)。一切都像我想要的那样工作:goroutines 从任务中获取一个文件,上传它,然后到下一个。

我的问题是:为什么 goroutine 不上传相同的文件?我已经对此进行了测试,似乎一个文件永远不会上传两次。频道在循环吗?

tasks := make(chan string, 10000)
var wg sync.WaitGroup

// create a limited number of routines
routineLimit := 30
for i := 0; i < routineLimit; i++ {
    wg.Add(1)
    go func() {
        // check to see if there is a new task
        for file := range tasks {
            Upload(file) // upload the file
        }
        wg.Done()
    }()
}

// get the files
files := GetFilePaths()
for _, file := range(files) {
        // add the file to the queue of tasks
    tasks <- file
}

wg.Wait()

【问题讨论】:

    标签: go


    【解决方案1】:

    当您的示例中单个通道有多个接收器时,输入将以随机顺序接收。

    【讨论】:

    • 但是文件只发送到一个goroutine,对吧?
    • 是的。频道不广播消息,只会发送给一个听众。
    猜你喜欢
    • 2017-10-12
    • 2013-04-14
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2011-04-04
    • 2014-10-24
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多