dongyuan8469 2019-01-28 11:33
浏览 221
已采纳

在goroutine中等待睡眠的主线程

Wrote this very basic code to understand channels.

  1. If there is a wait in a goroutine, why is the main goroutine waiting on it? I read that the main goroutine needs to have a wait time as the control is passed back to it immediately after invoking goroutine.

  2. Why are goroutines not designed like main thread and child threads in java where they can run in parallel?

func main() {
    channel := make(chan int)
    go func() {
        time.Sleep(3*time.Second)
    }()

    for {
        fmt.Println("../");
        <-channel
    }
}
  • 写回答

1条回答 默认 最新

  • dtkf64283 2019-01-28 11:40
    关注

    I think your main thread is waiting for something to come from the channel

    func main() {
        channel := make(chan int)
        go func() {
            time.Sleep(3*time.Second)
            channel <- 1 // Sending something to the channel to let the main thread continue
            channel <- 2
        }()
    
        for {
            fmt.Println("../");
            <-channel // Waiting for something to come from the channel
        }
    }
    

    regarding your specific questions:

    If there is a wait in a goroutine, why is the main goroutine waiting on it?

    It doesn't wait for it, it probably waiting on the channel.

    I read that the main goroutine needs to have a wait time as the control is passed back to it immediately after invoking goroutine.

    If your main wasn't waiting on the channel (or stack in an endless loop) it had finished and closed the application. GoRoutines closes with the main thread (like Java daemon threads)

    Why are goroutines not designed like main thread and child threads in java where they can run in parallel?

    They actually do (:

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

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题