Search code examples
gocancellation

When (how quickly) is a golang child function cancelled when cancelFunc() is called?


I want to access Redis and do a GET on two machines simultaneously. I'll use the first result I get and cancel the other call.

What I'm wondering is whether cancelFunc() breaks a go function immediately or whether it will wait for a specific event to happen before it notices the signal. The documentation just says:

Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers.

That doesn't say whether it happens immediately or whether a special cancellation point needs to be reached.

Any documentation I missed about that particular point?


Solution

  • Canceling a context simply closes its Done channel, it doesn't "kill" a goroutine or anything like that. Code that executes under the context has to do a select to notice the closure of the Done channel and abandon whatever work it's doing.

    However in many cases this work is already done for you. If the redis client method you're using to make requests accepts a context, then it's safe to assume that if that context is canceled, the client will handle the cancellation and the method will immediately return an error of context.Canceled — all you need to do is handle that error by quitting what you're doing.