Go project's main goroutine sleep forever?

Dev Zhou picture Dev Zhou · Apr 5, 2016 · Viewed 7.9k times · Source

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.

Answer

icza picture icza · Apr 5, 2016

"Sleeping"

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:

mu := sync.Mutex{}
mu.Lock()
mu.Lock()

Quitting

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.

Sleeping without blocking

The above constructs block the goroutine, so if you don't have other goroutines running, that will cause a deadlock.

If you don't want to block the main goroutine but you just don't want it to end, you may use a time.Sleep() with a sufficiently large duration. The max duration value is

const maxDuration time.Duration = 1<<63 - 1

which is approximately 292 years.

time.Sleep(time.Duration(1<<63 - 1))

If you fear your app will run longer than 292 years, put the above sleep in an endless loop:

for {
    time.Sleep(time.Duration(1<<63 - 1))
}