Sobes.tech
Senior

How can you terminate a goroutine? What methods are available?

sobes.tech AI

Answer from AI

In Go, goroutines do not have a built-in mechanism for forced termination from outside, so goroutine termination is usually implemented cooperatively. The main methods are:

  1. Using channels for stop signals — the goroutine listens to a channel, and upon receiving a signal, it terminates.

  2. Context (context.Context) — passing a context with cancellation capability, the goroutine periodically checks ctx.Done() and terminates upon cancellation.

  3. Flags or state variables — the goroutine checks the value of a variable and terminates if needed.

Example with context:

ctx, cancel := context.WithCancel(context.Background())

go func(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("Goroutine finished")
            return
        default:
            // work
        }
    }
}(ctx)

// At some point, call cancel() to stop the goroutine
cancel()

It is important that the goroutine correctly responds to the termination signal; otherwise, it will continue to run.