How to Signal a Go Routine to Halt without Blocking?

Patricia Arquette
Release: 2024-10-28 05:00:30
Original
126 people have browsed it

How to Signal a Go Routine to Halt without Blocking?

Signaling a Go Routine to Halt

In this scenario, a go routine needs to be instructed to cease operation. The primary challenge lies in achieving this signaling without introducing blocking behavior.

The proposed solution involves employing a secondary channel. However, conventional channel usage would lead to blocking if the go routine attempts to receive a signal from this channel while actively processing data.

Using a Select Case

To avoid blocking, the code can leverage a select case with a default clause. This allows the go routine to continue processing data until a signal is received from the secondary channel:

<code class="go">go func() {
    for {
        fmt.Println("working")
        time.Sleep(1 * time.Second)
        select {
        case <-tooLate:
            fmt.Println("stopped")
            return
        case proCh <- "processed": //this why it won't block the goroutine if the timer expirerd.
        default: // adding default will make it not block
        }
        fmt.Println("done here")
    }
}()</code>
Copy after login

By utilizing the default clause, the go routine can avoid blocking even when the timer expires.

Using a sync.Cond

Another approach involves utilizing a sync.Cond instead of a channel. A condition variable provides a way to wait and signal across goroutines.

Conclusion

With either a secondary channel with a default clause or a sync.Cond, you can effectively signal a go routine to stop running without resorting to blocking behavior.

The above is the detailed content of How to Signal a Go Routine to Halt without Blocking?. 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
Latest Articles by Author
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!