On Wed, Apr 12, 2023 at 7:29 AM Frank <francisbfwb...@gmail.com> wrote:
> Hi Gophers, > > So I've run into a situation where my code would run for a rather long > time (10minutes - ~1 hour). And I want to cancel it halfway sometimes. I > know I can use channel/context can check for channel message to return > early. But this requires explicitly checking for channel status and would > introduce many messy code blocks. Is it feasible (and good) for me to > listen to some signal and use panic to stop the execution once signal > received? > There are ways to reduce the boilerplate code. For instance: func LongTask(ctx context.Context) { canceled:=func() bool { select { case <-ctx.Done(): return true default: } return false } ... if canceled() { return } } Or, if this involves lots of nesting, you can define: canceled:=func() { select { case <-ctx.Done(): panic(errCanceled) default: } } so every now and then you can simply call canceled(). If you do this though, you need to recover: go func() { defer func() { if r:=recover(); r!=nil { if errors.Is(r,errCanceled) { // canceled } else { panic(r) } } }() LongTask(ctx) }() There is no way you can immediately stop a goroutine. Handling of a signal has to happen in a separate goroutine, and you would still need to check periodically in the actual goroutine you want to cancel. > Thanks! > Frank > > -- > 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/d8bb51be-4f21-4658-93a9-d0e197b9bdden%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/d8bb51be-4f21-4658-93a9-d0e197b9bdden%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- 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/CAMV2RqrKAo4br2jrUxEN4%3DL-y0AX-wVW4DOBMcRbc3KK4RZakA%40mail.gmail.com.