Home > Backend Development > Golang > 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 done?

WBOY
Release: 2024-02-10 12:27:10
forward
865 people have browsed it

当所有工作完成后,如何关闭由多个 goroutine 填充的通道?

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
    }
Copy after login

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)
}()
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template