When working with Go routines, knowing how to terminate them effectively becomes essential. Consider the following setup:
<code class="go">func startsMain() { go main() } func stopMain() { // TODO: Kill main } func main() { // Infinite loop }</code>
This setup creates an infinite loop in the goroutine named main. To terminate the loop, we need a way to control the goroutine from stopMain.
One effective approach to kill a goroutine is through channels and the select statement.
<code class="go">var quit chan struct{} func startLoop() { quit := make(chan struct{}) go loop(quit) } func stopLoop() { close(quit) } func loop(quit chan struct{}) { for { select { case <-quit: return default: // Do stuff } } }</code>
In this example, we use a zero-sized channel (chan struct{}) named quit to signal the goroutine to stop. The loop function repeatedly checks the quit channel using the select statement. When quit receives a value (indicating a stop request), the loop exits.
Go offers additional concurrency patterns for handling goroutines. Visit the Go Blog for more insights on these patterns.
To execute a function at regular intervals while avoiding CPU exhaustion, you can employ tickers.
<code class="go">import "time" // [...] func loop() { ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() for { select { case <-quit: return case <-ticker.C: // Do stuff } } }</code>
In this case, select blocks until either quit receives a value or ticker fires, allowing the function to execute at specified intervals.
The above is the detailed content of How do you effectively terminate a Goroutine in Go?. For more information, please follow other related articles on the PHP Chinese website!