英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论