Main Goroutine Persistence in Go Programs
One may encounter the question of how to prevent the main goroutine of a Go program from terminating prematurely. In other words, the goal is to keep the program running indefinitely, except through explicit user intervention.
"Sleeping" the Main Goroutine
There are several approaches to make the main goroutine wait forever without consuming CPU resources:
An empty select statement:
select {}
Receiving from an uninitialized channel:
<-make(chan int)
Receiving from a nil channel:
<-(chan int)(nil)
Sending to a nil channel:
(chan int)(nil) <- 0
Locking a locked sync.Mutex:
mu := sync.Mutex{} mu.Lock() mu.Lock()
Quitting the Program
If a mechanism to terminate the program is desired, a simple channel can serve the purpose:
var quit = make(chan struct{}) func main() { // Startup code... // Blocking (waiting for quit signal): <-quit } // Quitting in another goroutine: close(quit)
Sleeping without Blocking
An alternative approach to keeping the program running without blocking the main goroutine is to use a long sleep duration:
time.Sleep(time.Duration(1<<63 - 1))
For extremely long-running programs, a loop of such sleeping statements can be employed:
for { time.Sleep(time.Duration(1<<63 - 1)) }
The above is the detailed content of How Do I Prevent the Main Goroutine in a Go Program from Terminating Prematurely?. For more information, please follow other related articles on the PHP Chinese website!