On Monday, 19 December 2022 at 12:01:39 UTC Torsten Bronger wrote: > But would you agree that additional checking is necessary if > DoSomething does not have a ctx argument? >
Given that you're running DoSomething synchronously, it will always run to completion. So you'll always have a valid data value to send. Do you want to throw this value away if the context was cancelled in the mean time? You can do this: select { case <-ctx.Done(): return ctx.Err() default: select { case <-ctx.Done(): return ctx.Err() case out <- v: } } I included the second <-ctx.Done() because if out<-v is blocking for a long time, you still might want to be able to cancel Note that there is a race condition in this code: the context could be cancelled at any time even after DoSomething has completed. You have to allow that the value v *may or may not* be sent, depending on exactly when the cancellation signal arrived. Given that you already have a valid value from DoSomething you could decide to send it regardless, and then test for cancellation. But that depends on the receiver remaining ready to receive this value. for { v, err := DoSomething() if err != nil { return err } out <- v select { case <-ctx.Done(): return ctx.Err() } } TBH, I don't like the idea of a function sending or not sending a message on a channel randomly (depending on whether the context was cancelled); it's a recipe for deadlocks IMO. You should consider either closing the 'out' channel, or sending a termination message down it, to signal that there's no more data. I would use *that* as the trigger to terminate the receiver, rather than the context cancellation. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/24f681e9-a1b8-4061-8fb0-3cfb54847e07n%40googlegroups.com.