How do I block the program / goroutine?

Issue

I have a program that fires off two goroutines that provide services in the background. I then want to block the main goroutine and let them run in the background. I want to block ‘forever’ and I don’t care about clean exits. How should I do this? I could wait on channel and then never send anything down it. I could sleep in a loop. Neither feels quite right I thought there might be a simpler block() function I could call?

I’m currently doing this

var i chan int
<-i

Solution

You can use a sync.WaitGroup which you pass to each of your goroutine. This is the common way
to wait in the calling goroutine for its children.

However, in your case where you don’t care for the results this should do as well:

select {}

From the spec regarding select:

If there are no cases with non-nil channels, the statement blocks forever

This statement blocks forever while yielding control to the other goroutines.

Answered By – nemo

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.