简体   繁体   中英

Golang: forever channel

Just have a question, what is happening here?

forever := make(chan bool)

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever

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?

The code in the question is probably coming from the RabbitMQ golang tutorial here .

Here's a more extended chunk of it with some commends of my own:

    ...
    // create an unbuffered channel for bool types.
    // Type is not important but we have to give one anyway.
    forever := make(chan bool) 

    // fire up a goroutine that hooks onto msgs channel and reads
    // anything that pops into it. This essentially is a thread of
    // execution within the main thread. msgs is a channel constructed by
    // previous code.
    go func() {
        for d := range msgs {
            log.Printf("Received a message: %s", d.Body)
        }
    }()

    log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
    // We need to block the main thread so that the above thread stays
    // on reading from msgs channel. To do that just try to read in from
    // the forever channel. As long as no one writes to it we will wait here.
    // Since we are the only ones that know of it it is guaranteed that
    // nothing gets written in it. We could also do a busy wait here but
    // that would waste CPU cycles for no good reason.
    <-forever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM