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 在工控机(Ubuntu系统)上外接USB蓝牙硬件进行蓝牙通信
    • ¥15 关于PROCEDURE和FUNCTION的问题
    • ¥100 webapi的部署(标签-服务器)
    • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
    • ¥15 C语言除0问题的检测方法
    • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
    • ¥15 macos13下 ios交叉编译的问题
    • ¥15 bgz压缩文件怎么打开
    • ¥15 封装dll(引入了pcl的点云设计库)
    • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发