go - 第一个协程示例,奇怪的结果

标签 go goroutine

这个例子取自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/

相关文章:

go - 无法推断函数构造函数的泛型参数中的类型

unit-testing - 如何在 Ubuntu 18.04 上使用 -msan 选项运行 go test?

go - Go 中令人尴尬的并行任务的惯用解决方案是什么?

go - 所有 goroutines 都处于休眠状态

concurrency - 不同输入数据的 Goroutine 执行时间

function - 如何自引用一个函数?

go - 为结构字段分配默认值

go - 等待 gin HTTP 服务器启动

go - 如何在 Golang 中并行生成组合

go - 为什么 goroutine 执行命令在运行之间是相同的