简体   繁体   English

为什么主goroutine总是第二个被调用

[英]why main goroutine always be the second to be invoked

package main
import (
  "sync"
  "time"
  )
func main() {
  var wg sync.WaitGroup

  wg.Add(1)

  go func() {         //A
    wg.Wait()
    println("wait exit")
  }()

  go func() {
    time.Sleep(time.Second)
    wg.Done()
  }()

  wg.Wait()
  println("main exit")
}

result: 结果:

wait exit
main exit

Why don't main goroutine execute println("main exit") first, and main thread dead and then discard A goroutine? 为什么主goroutine不先执行println(“ main exit”),然后主线程死掉,然后丢弃A goroutine? It keeps printing like the result shows 像结果显示一样保持打印

Chance. 机会。

There's nothing in the language spec that says your "wait exit" should execute either before or after "main exit". 语言规范中没有任何内容表明您的“等待退出”应该在“主退出”之前或之后执行。

Chances are if you run the program enough times, sometimes "main exit" will run first. 如果您足够长时间运行该程序,则有时“主出口”将首先运行。 But also maybe not. 但也可能不会。 The results are not defined, and depend on the runtime state and implementation. 结果未定义,并且取决于运行时状态和实现。 As such results may even change between Go versions. 因此,结果甚至可能在Go版本之间发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM