duanjing7459 2015-04-21 05:02
浏览 56
已采纳

Goroutine和for循环

All I want to do is to send one value to the channel and return from the main() function and exit the program right after I receive one value from the channel ch.

But this keeps running forever:

ch := make(chan int)

for {
    go func() {
        ch <- 1
    }()
}

<-ch

How do I return with this for loop after I receive one value from the channel?

And why does this run forever?

Go playground link is here

http://play.golang.org/p/EvmT6Pw96Y

  • 写回答

1条回答 默认 最新

  • douzuo5504 2015-04-21 05:16
    关注

    Since the for loop runs forever, your code runs forever. Receiving from ch after the for loop is never reached.

    If you want your code to exit sometime, you have to end the for loop sometime, e.g. make it run only a certain number of iterations:

    for i := 0; i < 5; i++ {
        ...
    }
    

    So if you only run 5 iterations (like in my example), after the for loop receiving from ch will be executed which may block (because ch is unbuffered) if other goroutines have not yet run, and at least one of the started goroutines will be executed which sends a value on the channel which may trigger the main goroutine to continue (because its blocking operating is no longer blocking).

    Also note that the Go Memory Model only guarantees that certain events happen before other events, you have no guarantee how 2 concurrent goroutines are executed. You have no guarantee that the goroutines started in the for loop will start to execute before the main goroutine gets blocked at receiving from ch.

    Usually when a goroutine gets blocked (e.g. blocking channel receive operation), the runtime may schedule another goroutine to run.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab