dongzhi1822 2017-11-13 10:24
浏览 78
已采纳

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 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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?