Is there any API to let the main
goroutine sleep forever?
In other words, I want my project always run except when I stop it.
Is there any API to let the main
goroutine sleep forever?
In other words, I want my project always run except when I stop it.
You can use numerous constructs that block forever without "eating" up your CPU.
For example a select
without any case
(and no default
):
select{}
Or receiving from a channel where nobody sends anything:
<-make(chan int)
Or receiving from a nil
channel also blocks forever:
<-(chan int)(nil)
Or sending on a nil
channel also blocks forever:
(chan int)(nil) <- 0
Or locking an already locked sync.Mutex
:
mux := sync.Mutex{}
mux.Lock()
mux.Lock()
If you do want to provide a way to quit, a simple channel can do it. Provide a quit
channel, and receive from it. When you want to quit, close the quit
channel as "a receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received".
var quit = make(chan struct{})
func main() {
// Startup code...
// Then blocking (waiting for quit signal):
<-quit
}
// And in another goroutine if you want to quit:
close(quit)
Note that issuing a close(quit)
may terminate your app at any time. Quoting from Spec: Program execution:
Program execution begins by initializing the main package and then invoking the function
main
. When that function invocation returns, the program exits. It does not wait for other (non-main
) goroutines to complete.
When close(quit)
is executed, the last statement of our main()
function can proceed which means the main
goroutine can return, so the program exits.
It depends on use cases to choose what kind of sleep you want.
@icza provides a good and simple solution for literally sleeping forever, but I want to give you some more sweets if you want your system could shutdown gracefully.
You could do something like this:
func mainloop() {
exitSignal := make(chan os.Signal)
signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM)
<-exitSignal
systemTeardown()
}
And in your main:
func main() {
systemStart()
mainloop()
}
In this way, you could not only ask your main to sleep forever, but you could do some graceful shutdown stuff after your code receives INT
or TERM
signal from OS, like ctrl+C
or kill
.