How do you effectively terminate a Goroutine in Go?

DDD
Release: 2024-10-30 13:15:03
Original
682 people have browsed it

How do you effectively terminate a Goroutine in Go?

Killing a Goroutine in Go

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>
Copy after login

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.

Solution: Using a Channel and select

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>
Copy after login

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.

Other Concurrency Patterns

Go offers additional concurrency patterns for handling goroutines. Visit the Go Blog for more insights on these patterns.

Using Timers

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!