
当所有工作完成后,如何关闭由多个goroutine填充的通道是一个经常被提及的问题。在Go语言中,关闭一个通道是一种通知接收方没有更多数据的方式。通过关闭通道,接收方可以及时得知发送方已经完成了所有的发送操作。在多个goroutine填充的通道中,我们可以使用一个计数器来跟踪还有多少个goroutine在向通道发送数据。当计数器减为0时,表示所有的工作都已完成,此时我们可以安全地关闭通道。关闭通道后,接收方可以通过在接收表达式中使用额外的变量来判断通道是否已关闭。通过这种方式,我们可以保证在所有工作完成后正确关闭由多个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 填充的通道?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号