简体   繁体   中英

What happens when returning on for-select loop with running goroutines

I'm trying to figure how can I shorten run times as much as possible when waiting for results on multiple goroutines. The idea is doing a for-select loop on retrieving messages from a channel (result channel) and breaking out of the loop when a result is false. Subsequently, potentially one or more goroutines are left running and I don't quite know what would happen in the background.

Consider this:

results := make(chan bool, int NumRequests)
go DoSomething(results) // DoSomething sends the result on results channel
go DoSomething(results) // DoSomething sends the result on results channel
go DoSomething(results) // DoSomething sends the result on results channel
for {
    select {
    case r := <- results:
        if !r {
            return
        }
    }
}

My question is - What would happen if I return while there are goroutines trying to sent their result to the channel? I've made a buffered results channel as seen above so the goroutines wouldn't deadlock while running. What would happen memory-wise when doing this? Will there be a goroutine leakage? What is the idiomatic way of doing something like this?

This is the exact purpose behind cancellable contexts. Take a look at the example for context.WithCancel , it shows how to do exactly what you describe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM