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.

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

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器