Sobes.tech
Junior — Middle

How can you forcibly stop multiple goroutines that are running at once in Go?

sobes.tech AI

Answer from AI

In Go, to forcibly stop multiple goroutines, the common mechanism is cancellation via context.Context.

Main idea:

  • Create a context with cancellation (context.WithCancel or context.WithTimeout).
  • Each goroutine accepts this context and periodically checks if it has been canceled.
  • When the cancel function (cancel()) is called, all goroutines receive the signal and can terminate gracefully.

Example:

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

for i := 0; i < 5; i++ {
    go func(id int) {
        for {
            select {
            case <-ctx.Done():
                fmt.Printf("Goroutine %d stopped\n", id)
                return
            default:
                // goroutine work
                time.Sleep(100 * time.Millisecond)
            }
        }
    }(i)
}

// After some time, stop all goroutines
time.Sleep(1 * time.Second)
cancel()

// Wait for completion (e.g., via sync.WaitGroup)

This approach allows centralized control over stopping multiple goroutines and avoids issues with uncontrolled termination.

How can you forcibly stop multiple goroutines that… - sobes.tech