登录
首页 >  Golang >  Go问答

多个 Goroutine 填充通道后的关闭方法是什么?

来源:stackoverflow

时间:2024-02-14 19:15:22 275浏览 收藏

今天golang学习网给大家带来了《多个 Goroutine 填充通道后的关闭方法是什么?》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我试图遵循“不要通过共享内存来通信,而是通过通信来共享内存”的Go方式,并使用通道来异步地传达要完成的任务并发送回处理任务的结果。

为了简单起见,我已将通道类型更改为 int,而不是它们真正的结构。并用 time.Sleep() 替换了长时间的处理。

如何在发回所有任务结果后关闭 ProducedResults ,以便此代码不会卡在最后一个 for

quantityOfTasks:= 100
    quantityOfWorkers:= 60
    remainingTasks := make(chan int)
    producedResults := make(chan int)

    // produce tasks
    go func() {
        for i := 0; i < quantityOfTasks; i++ {
            remainingTasks <- 1
        }
        close(remainingTasks)
    }()

    // produce workers
    for i := 0; i < quantityOfWorkers; i++ {
        go func() {
            for taskSize := range remainingTasks {
                // simulate a long task
                time.Sleep(time.Second * time.Duration(taskSize))
                // return the result of the long task
                producedResults <- taskSize
            }
        }()
    }

    // read the results of the tasks and agregate them
    executedTasks := 0
    for resultOfTheTask := range producedResults { //this loop will never finish because producedResults never gets closed
        // consolidate the results of the tasks
        executedTasks += resultOfTheTask
    }

正确答案


您希望在写入该通道的所有 goroutine 返回后关闭该通道。您可以使用 WaitGroup 来实现:

wg:=sync.WaitGroup{}

for i := 0; i < quantityOfWorkers; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for taskSize := range remainingTasks {
                //simulate a long task
                time.Sleep(time.Second * time.Duration(taskSize))
                //return the result of the long task
                producedResults <- taskSize
            }
        }()
}

go func() {
  wg.Wait()
  close(producedResults)
}()

到这里,我们也就讲完了《多个 Goroutine 填充通道后的关闭方法是什么?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>