Home >Backend Development >Golang >How Can I Keep the Main Goroutine Running Indefinitely in Go?
Go offers an array of mechanisms to keep the main goroutine running indefinitely without consuming processing power. Consider these strategies:
Select without Cases: Blocking forever without CPU consumption is achievable through a select statement with no cases or default clause:
select {}
Receiving from an Empty Channel: The main goroutine can be suspended indefinitely by continuously receiving from an empty channel:
<-make(chan int)
Receiving from a Nil Channel: Similarly, receiving from a nil channel yields the same effect:
<-chan int(nil)
Sending to a Nil Channel: Sending to a nil channel also suspends the main goroutine permanently:
(chan int)(nil) <- 0
Locking a Pre-Locked Mutex: Locking an already locked mutex effectively stalls the main goroutine:
mu := sync.Mutex{} mu.Lock() mu.Lock()
To facilitate a graceful exit, a dedicated quit channel can be utilized. When the need arises to terminate the program, this channel is closed:
var quit = make(chan struct{}) func main() { defer close(quit) // Application code... <-quit }
In a separate goroutine, closing the quit channel triggers the main goroutine's exit:
close(quit)
If the goal is to keep the main goroutine from terminating without blocking it, the time.Sleep() function can be employed with a sufficiently large duration, capped at approximately 292 years:
time.Sleep(time.Duration(1<<63 - 1))
For extended durations, consider an endless loop incorporating the above time.Sleep():
for { time.Sleep(time.Duration(1<<63 - 1)) }
The above is the detailed content of How Can I Keep the Main Goroutine Running Indefinitely in Go?. For more information, please follow other related articles on the PHP Chinese website!