Sobes.tech
Junior — Middle

Kuidas sundida mitu töötavat goroutine'i Go-s peatuma?

sobes.tech AI

Vastus AI-lt

In Go, to forcibly stop multiple running goroutines, the common approach is to use a cancellation mechanism via context (context.Context).

Main idea:

  • Create a cancellable context (context.WithCancel or context.WithTimeout).
  • Each goroutine receives 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 properly.

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 their completion (e.g., using sync.WaitGroup)

This approach allows centralized management of stopping multiple goroutines and avoids issues with uncontrolled termination.