dongzhi1822
2017-11-13 10:24 阅读 69
已采纳

Golang:永远的频道

Just have a question, what is happening here?

forever := make(chan bool)

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    drqvsx1228 drqvsx1228 2017-11-13 10:25

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

    And since noone 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 golang channels used for?

    点赞 评论 复制链接分享
  • dtjzpg5313 dtjzpg5313 2019-07-18 13:51

    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
    
    点赞 评论 复制链接分享

相关推荐