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

huangapple go评论79阅读模式
英文:

why main goroutine always be the second to be invoked

问题

为什么主 goroutine 不先执行 println("main exit"),然后主线程结束并丢弃 A goroutine?根据结果显示,它一直在打印。

英文:
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?
It keeps printing like the result shows

答案1

得分: 2

机会。

在语言规范中没有规定你的“wait exit”应该在“main exit”之前还是之后执行。

如果你运行程序足够多次,有时候“main exit”会先执行。但也有可能不会。结果是不确定的,取决于运行时状态和实现。因此,结果甚至可能在不同的Go版本之间发生变化。

英文:

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.

huangapple
  • 本文由 发表于 2017年6月20日 23:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/44657084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定