Here's the code snippet:
for !done && outstanding > 0 {
select {
case signals := <- input:
outstanding++
go func() { results <- FFT(signals) }()
case res <- results:
outstanding--
output <- results
case <- ctx.Done():
done = true
}
}
In this video Richard Fliam says that:
In this code snippet we're farming out some work to multiple cores for FFTs. When cancellation is done on all outstanding results are collected and sent before the function returns. If we did not collect the results in this case we would have a memory leak. You can see that's because I'm not selecting against the Done context in that go func.
But when there are some outstanding results (the outstanding variable is greater than zero) and the operation is cancelled then the done variable is set to true and then the condition of the for loop would evaluate to false, so the outstanding results would not be collected.
Why does he say that the outstanding results are collected before the the function returns?
I'm new to go. Maybe I don't understand something fundamental concept.
Update:
IMO the outstanding results would always be collected if the condition of the for loop was the following:
// logical OR instead of AND
for !done || outstanding > 0 { ... }
Because when the operation is cancelled and there are still some outstanding results the condition of the for loop would evaluate to true. If all outstanding results arrive the for loop will end.