Coordinating the Termination of Multiple Goroutines
When working with multiple goroutines in Golang, it's often necessary to synchronize their execution such that they terminate together. One common approach is to utilize a channel to signal completion. However, this method can lead to a "write to closed channel" panic if the goroutines do not terminate in the expected order.
Employing Contexts for Goroutine Coordination
A better solution involves using contexts. Contexts provide a mechanism for communication and cancellation between goroutines. Here's how you can implement this in Go:
package main import ( "context" "sync" ) func main() { // Create a context and a function to cancel it ctx, cancel := context.WithCancel(context.Background()) // Initialize a wait group to track goroutine completion wg := sync.WaitGroup{} wg.Add(3) // Add 3 goroutines to the wait group // Launch three goroutines // Each goroutine listens for the context to be done go func() { defer wg.Done() for { select { caseIn this example, when the third goroutine completes its operations, it cancels the context. This propagates the cancellation to the other goroutines, causing them to terminate as well. By using contexts, we eliminate the potential for panic and ensure that all goroutines coordinate their termination effectively.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3