Synchronizing Goroutines with Context
In Go, there is a challenge when working with goroutines: ensuring their orderly termination. Consider a scenario with multiple goroutines operating independently, but you want them to synchronize such that when one goroutine finishes, the others should also exit.
The code snippet provided includes two goroutines that continually run. If an error occurs within one goroutine, you intend to end both. Using a channel for signaling completion can lead to panics due to writes to closed channels.
The recommended approach for such scenarios is to employ Go's context package, which allows for communication between goroutines.
In the code example below, a background context is created with a cancel function using context.WithCancel. A sync.WaitGroup is created to track the number of running goroutines.
package main import ( "context" "sync" ) func main() { ctx, cancel := context.WithCancel(context.Background()) wg := sync.WaitGroup{} wg.Add(3)
Three goroutines are started. The first two goroutines continuously run, waiting for a signal from the context. Upon receiving the signal, they exit gracefully.
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 } } }()
The third goroutine performs an operation and then calls the cancel function to signal the completion of its task. This action prompts the context to close, triggering the other two goroutines to exit.
go func() { defer wg.Done() // your operation // call cancel when this goroutine ends cancel() }()
Finally, the wg.Wait function waits for all three goroutines to complete before the main routine exits.
wg.Wait() }
This context-based approach ensures that when any of the goroutines finishes, the others are notified and terminate gracefully, providing a clean and efficient way to handle goroutine synchronization.
The above is the detailed content of How Can Go's Context Package Ensure Graceful Termination of Multiple Goroutines?. For more information, please follow other related articles on the PHP Chinese website!