How to manage go routines and stop a specific go routine

528 Views Asked by At

This is an abstract example to real case, I have to stop some specific go routine created by a func A by calling func B

func A(context, interval, ...params) {
 go (interval) {
    tk := time.ticker(interval)
    for {
      select {
       case <- tk.C:
        err := func C(params)
     }
    }
  }(interval)
}

(func A) creates go routine executing (func C) at repeated interval with specific parameters.

func B(context, ...params) {
  // stop go routine that runs func C with specific params.
}

(func B) needs to stop go routine running (func C) with given parameters. Also how can I handle cases like error and context timeout in (func A).

note: pseudo code provided, sorry real code cannot be shared.

1

There are 1 best solutions below

0
On

I believe you're looking for context.Done.

Done returns a channel that's closed when work done on behalf of this context should be canceled.

select {
case <-ctx.Done():
    // context was cancelled, stop goroutine
    return
case <-tk.C:
    C(params...)
}

Working example: https://go.dev/play/p/wSUHSHCse7D

There is no simple way of finding goroutine based on params so you have to adjust your code a little bit to select which context you want to cancel.