Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I block the program / goroutine?

Tags:

go

goroutine

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
like image 503
Joe Avatar asked Sep 12 '13 18:09

Joe


People also ask

How do you stop Goroutine?

Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.

Is Goroutine blocked?

When we send data into the channel using a GoRoutine, it will be blocked until the data is consumed by another GoRoutine. When we receive data from channel using a GoRoutine, it will be blocked until the data is available in the channel.

What is Goroutine used for?

Goroutines are useful when you want to do multiple things simultaneously. For example, if you have ten things you want to do at the same time, you can do each one on a separate goroutine, and wait for all of them to finish.

What is Goroutine and channel?

A goroutine is a function that runs independently of the function that started it. Sometimes Go developers explain a goroutine as a function that runs as if it were on its own thread. Channel is a pipeline for sending and receiving data. Think of it as a socket that runs inside your program.


1 Answers

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.

like image 92
nemo Avatar answered Sep 28 '22 07:09

nemo