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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With