普通网友 2016-05-12 20:24
浏览 10
已采纳

为什么我需要睡两次才能看到goroutine?

I've written this little program with go. About go keyword, I just know that when I call a function in this manner, is executed simultaenously. What I've tried to execute this code without time.Sleep(), but no output is generated. I need to add time.Sleep(1000) twice. One time.Sleep statement is not enough. Why?

package main

import (
    "fmt"
    "time"
)

func doSomething(integer int) {
    fmt.Println(integer)
}

func main() {
    i := 1

    for i <= 10 {
        go doSomething(i)
        i++
    }

    time.Sleep(1000)
    time.Sleep(1000)
}
  • 写回答

2条回答 默认 最新

  • dongshou9343 2016-05-12 20:28
    关注

    That's because when you call a function with go (ie as a goroutine) it is run in the background and execution continues. In this case, you have nothing for the program to do after invoking the goroutine so it just completes and you see no output. Why do you need two? Well you don't, it's just the 1 second sleep wasn't long enough, if you had time.Sleep(2000) you'd probably get the same result (though it's not guaranteed). Generally when using a goroutine, you need some kind of blocking statement some where. The simplest way to do this, imo, is to pass a channel to the goroutine and then receive from it.

    This isn't the most useful example due to the structuring of your code, but here's a modified version of your program that will block until the first goroutine completes. Since you're actually invoking 10 goroutines, you would need a bit more robust logic to block until of them complete but a more reasonable solution would be to put the loop in the gouroutine, rather than invoking 10 goroutines. https://play.golang.org/p/66g9u8Bhjj

    Also, check out this more realistic example in the go tour; https://tour.golang.org/concurrency/2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单