Home >Backend Development >Golang >How to Signal a Go Routine to Halt without Blocking?
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.
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>
By utilizing the default clause, the go routine can avoid blocking even when the timer expires.
Another approach involves utilizing a sync.Cond instead of a channel. A condition variable provides a way to wait and signal across goroutines.
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!