Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: forever channel

Tags:

go

channel

Just have a question, what is happening here?

forever := make(chan bool)

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
like image 335
Rudziankoŭ Avatar asked Nov 13 '17 10:11

Rudziankoŭ


1 Answers

That code creates an unbuffered channel, and attempts to receive from it.

And since no one ever sends anything on it, it's essentially a blocking forever operation.

The purpose of this is to keep the goroutine from ending / returning, most likely because there are other goroutines which do some work concurrently or they wait for certain events or incoming messages (like your log message says).

And the need for this is that without this, the application might quit without waiting for other goroutines. Namely, if the main goroutine ends, the program ends as well. 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.

Check out this answer for similar and more techniques: Go project's main goroutine sleep forever?

For an introduction about channels, see What are channels used for?

like image 87
icza Avatar answered Sep 25 '22 13:09

icza