这个例子取自tour.golang.org/#63
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")
}
输出
hello
world
hello
world
hello
world
hello
world
hello
为什么 world
只打印了 4
次而不是 5
?
编辑: 答案可以引用自golang specification :
Program execution begins by initializing the main package and then invoking the function main. When the function main returns, the program exits. It does not wait for other (non-main) goroutines to complete.
最佳答案
当你的 main 函数结束时,你的程序就结束了,即所有的 goroutines 都终止了。
您的 main 在 go say("world")
完成之前终止。如果你在 main 结束时睡了一段时间,你应该会看到最后一个世界。
关于go - 第一个协程示例,奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18599875/