


How to close a channel filled by multiple goroutines when all work is done?
How to close a channel filled by multiple goroutines when all work is completed is an often mentioned question. In Go, closing a channel is a way of notifying the receiver that there is no more data. By closing the channel, the receiver can know in time that the sender has completed all sending operations. In a channel filled with multiple goroutines, we can use a counter to track how many more goroutines are sending data to the channel. When the counter drops to 0, all work has been completed and we can safely close the channel. After closing the channel, the receiver can determine whether the channel has been closed by using additional variables in the receive expression. In this way, we can ensure that channels filled by multiple goroutines are properly closed after all work is completed, thus avoiding resource leaks and deadlock issues.
Question content
I'm trying to follow the Go way of "don't communicate over shared memory, but share memory through communication" and use channels to asynchronously communicate what is to be done and send Return the results of processing tasks.
For simplicity, I've changed the channel types to int, rather than their true structures. And replaced long processing with time.Sleep()
.
How do I close ProducedResults
after all task results have been sent back so that this code doesn't get stuck on the last 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 }
Workaround
You want to close the channel after all goroutines writing to the channel have returned. You can use WaitGroup to achieve:
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) }()
The above is the detailed content of How to close a channel filled by multiple goroutines when all work is done?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...
