Home >Backend Development >Golang >How to Gracefully Kill Multiple Goroutines Simultaneously in Go?
How to Kill Multiple Goroutines at Once in Go
In Go, you may encounter scenarios where you need to terminate multiple goroutines simultaneously. This is especially useful when one goroutine's completion should trigger the termination of others.
Consider the following code snippet:
func main() { go func() { ... if err != nil { return } }() go func() { ... if err != nil { return } }() }
In this case, you want to ensure that when one of the goroutines returns, the other should also exit. A common approach to achieve this is to use channels for signaling. However, this may lead to a write to closed channel panic.
A reliable solution to this problem is leveraging Go's context mechanism. Context allows you to establish communication between routines and signal when an operation is completed or canceled. Here's an example:
package main import ( "context" "sync" ) func main() { ctx, cancel := context.WithCancel(context.Background()) wg := sync.WaitGroup{} wg.Add(3) go func() { defer wg.Done() for { select { // msg from other goroutine finish case <-ctx.Done(): // end } } }() go func() { defer wg.Done() for { select { // msg from other goroutine finish case <-ctx.Done(): // end } } }() go func() { defer wg.Done() // your operation // call cancel when this goroutine ends cancel() }() wg.Wait() }
In this example, we create a context that can be passed to goroutines to check for termination signals. When the third goroutine completes its operation, it calls cancel(), which sends a signal to both goroutines waiting for its completion. As a result, all goroutines terminate gracefully.
The above is the detailed content of How to Gracefully Kill Multiple Goroutines Simultaneously in Go?. For more information, please follow other related articles on the PHP Chinese website!