Home >Backend Development >Golang >How to Gracefully Terminate Multiple Go Routines Using Context?
How to Synchronize Multiple Go Routines with Context
To synchronize multiple goroutines, allowing them to terminate when one of them returns, context provides an effective solution.
Explanation:
The sample code creates two goroutines. To synchronize them, a context.Context is initiated and provided to both goroutines. Each goroutine enters a select {} loop, listening for messages from the context.
When an error occurs or a specific condition is met:
Code Sample:
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() }
Advantages of Using Context:
The above is the detailed content of How to Gracefully Terminate Multiple Go Routines Using Context?. For more information, please follow other related articles on the PHP Chinese website!