gpt4 book ai didi

go - fmt.Print in go routine *may* not output when master thread is loop

转载 作者:IT王子 更新时间:2023-10-29 01:56:30 25 4
gpt4 key购买 nike

以下代码与 https://play.golang.org/p/X1-jZ2JcbOQ 中的一样

package main
import (
"fmt"
)
func p(s string) {
fmt.Println(s)
}

func main() {
go fmt.Println("1")
go p("2")
for {} // infinite loop
}

在使用 golang 1.11 的 Windows 中肯定打印 1 2 但在使用 golang 1.11.4 的 Linux 中绝对不打印任何内容。我能理解前者的行为,但不能理解后者。为什么go程序一直不运行非master线程?

这背后有什么原因吗?

最佳答案

Go Playground 以 GOMAXPROCS=1 运行。在 Playground 上试试这个:

package main

import (
"fmt"
"runtime"
)

func main() {
fmt.Println(runtime.GOMAXPROCS(0))
}

当你在本地运行时,你可能会有更高的 GOMAXPROCS 值。

即使在 playground 上,如果你通过引入 Sleep [ https://play.golang.org/p/QquMPZSd6kI] 取消调度主 goroutine,你也可以看到打印工作:

func main() {
go fmt.Println("1")
go p("2")

time.Sleep(time.Second)
for {}
}

在开始时更改 GOMAXPROCS:

    runtime.GOMAXPROCS(2)

关于go - fmt.Print in go routine *may* not output when master thread is loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com