dr637349 2019-09-15 16:22
浏览 64
已采纳

在golang中晃来晃去的goroutine

In the following code

  1. What happens to goroutine1?(at the end of program we have three goroutine goroutine1 without any functionality)
  2. What happens to channel?(when we make a channel in loop it release the previous channel memory? close it? or something else?)
func main() {
    for i := 1; i <= 3; i += 1 {
        ch := make(chan int)

        // gorutine1
        go func() {
            time.Sleep(3 * time.Second)
            ch <- i
            fmt.Println("gorutine1 end")
        }()

        // gorutine2
        go func() {
            time.Sleep(1 * time.Second)
            ch <- i+1000
            fmt.Println("gorutine2 end")
        }()

        fmt.Println("loop", <-ch)
    }

    time.Sleep(10 * time.Second)
    fmt.Println("main end")
}

Run above code here

  • 写回答

1条回答 默认 最新

  • douyu4535 2019-09-15 16:51
    关注

    For i=1, the loop creates two goroutines, and starts waiting to read from the channel. goroutine2 writes first and terminates. The channel is read, and then i becomes 2. goroutine1 will wait forever, because nobody will read from the channel again. You create a new channel, and do the same thing. When everything is said and done, you have three instances of goroutine1 waiting to write to three different channels.

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

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3