Thank you very much. I understand that we can use context.Context to resolve the network blocking problem in long-running function if the network library support passing a context parameter.
But for the CPU-bound code, Is the following implementation mentioned by axel the only way to make a function exit earlier? select { case <-ctx.Done(): return ctx.Err() default: } For example, goroutine is executing a task to update a DNS record and then wait some time until the DNS record takes effect in some name servers. It may take some seconds even minutes to make the DNS record take effect in the name server. In this case, seems I can't cancel the running goroutine except that we add the above select at every for loop or wait timer, or I change the design to split these time-consuming operations into different goroutine. Both seem not so good. On Tuesday, January 11, 2022 at 1:04:15 PM UTC-8 Ian Lance Taylor wrote: > On Tue, Jan 11, 2022 at 12:15 PM 'Axel Wagner' via golang-nuts > <golan...@googlegroups.com> wrote: > > > > The best way to do this is to plumb a context.Context through all > long-running functions - in particular, anything talking to the network. > > Most RPC and network frameworks provide a way to pass a Context, so > consistently doing this will more or less transparently cancel your > business logic ASAP. > > For purely CPU bound code, this is a bit more awkward, because you > indeed have to intersperse code like > > select { > > case <-ctx.Done(): > > return ctx.Err() > > default: > > } > > to make the code return early. But that should be relatively rare. > > Yes. See also https://go.dev/blog/context . > > Ian > -- 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/d1898f67-d1e0-4276-af92-016b82866de4n%40googlegroups.com.