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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog