dongshengheng1013 2017-09-11 00:26
浏览 26
已采纳

“ Tour of Go”中的并发

I'm going through 'A Tour of Go' and have been editing most of the lessons to make sure I fully understand them. I have a question regarding: https://tour.golang.org/concurrency/1

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")
}

Leaving main the way it is produces a random ordering of hellos and worlds because the threads are executing in different orders each time the program runs. I have two questions:

  1. If I remove go from the line with world and add it to the line with hello, world is printed 5 times and hello is not printed at all. Why is that?
  2. If I add go in front of both lines, nothing is printed at all. Why is that?

I have some experience with concurrency with C++ (although it was a while ago) and some more recent experience with Python, but would describe my overall experience with concurrency fairly novice-level.

Thanks!

  • 写回答

1条回答 默认 最新

  • doudiyu1639 2017-09-11 00:35
    关注

    The program terminates before you get a chance to see the results.

    You can fix this by adding a statement that ensures main doesn't exit before the other routines are finished.


    From Golang - Concurrency:

    With a goroutine we return immediately to the next line and don't wait for the function to complete.

    They give a code example:

    package main
    
    import "fmt"
    
    func f(n int) {
      for i := 0; i < 10; i++ {
        fmt.Println(n, ":", i)
      }
    }
    
    func main() {
      go f(0)
      var input string
      fmt.Scanln(&input)
    }
    

    In regards to the code above:

    This is why the call to the Scanln function has been included; without it the program would exit before being given the opportunity to print all the numbers.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么