dongshimao7115 2016-04-17 14:11
浏览 22
已采纳

试图了解goroutines

I've been playing around with the following code from A Tour of Go, but I don't understand what is going on when I apply some minor changes. The original code is this

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}

and it produces this

world
hello
hello
world
world
hello
hello
world
world
hello

which is OK: five times hello, five times world. I starts to get strange when I call

say("world")
go say("hello")

Now the output is just

world
world
world
world
world

No hello whatsoever. It gets even weirder with two goroutines

go say("world")
go say("hello")

Now there is no output at all. When I change i < 5 to i < 2 and call

go say("world")
say("hello")

I get

world
hello
hello

What am I missing here?

  • 写回答

4条回答 默认 最新

  • dongyou7472 2016-04-17 14:17
    关注

    In the case of

     say("world")
     go say("hello")
    

    The "world" call must complete before the "hello" goroutine is started. The "hello" goroutine does not run or complete because main returns.

    For

    go say("world")
    go say("hello")
    

    the goroutines do not run or complete because main returns.

    Use sync.WaitGroup to prevent main from exiting before the goroutines complete:

    func say(wg *sync.WaitGroup, s string) {
      defer wg.Done()
      for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
      }
    }
    
    func main() {
      var wg sync.WaitGroup
      wg.Add(2)
      go say(&wg, "world")
      go say(&wg, "hello")
      wg.Wait()
    }
    

    playground example

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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真