fmt.go例程中的打印*主线程循环时可能不会输出
The following code as is in 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
}
prints 1 2 definitely in Windows with golang 1.11 but prints nothing definitely in Linux with golang 1.11.4. I can understand the former behavior but not the latter. Why is the go program not running non-master thread all the time?
Is there a reason behind this?
以下代码与 https://play.golang.org/p/X1-jZ2JcbOQ p>
包main
import(
“ fmt”
)
func p(s字符串){
fmt.Println(s)
}
func main(){
go fmt.Println(“ 1”)
go p(“ 2“)
for {} //无限循环
}
code> pre>
在使用golang 1.11的Windows中绝对打印1 2,但在使用golang 1.11的Linux中绝对不打印任何内容 0.4。 我可以理解前者的行为,但不能理解后者。 为什么go程序始终不运行非主线程? p>
这背后有原因吗? p>
div>
The Go Playground runs with GOMAXPROCS=1. Try this on the playground:
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println(runtime.GOMAXPROCS(0))
}
When you are running locally, you would perhaps have higher value of GOMAXPROCS.
Even on playground, you can see the printing work if you deschedule the main goroutine as below by introducing a Sleep [https://play.golang.org/p/QquMPZSd6kI]:
func main() {
go fmt.Println("1")
go p("2")
time.Sleep(time.Second)
for {}
}
OR
Change the GOMAXPROCS at start:
runtime.GOMAXPROCS(2)