英文:
Why wont go print from thread after infinit go routine on Ubuntu
问题
我有一个在Ubuntu上的Go程序,代码如下:
package main
import (
"fmt"
"time"
)
func main() {
count := 2
for i := 0; i < count; i++ {
go ping()
}
for {}
}
func ping() {
for {
time.Sleep(time.Second)
fmt.Println("hello world")
}
}
我的想法是调用两次go例程,在每次运行go例程时等待1秒钟,然后打印"hello world"。然而,在Ubuntu上运行这个程序时没有输出。在OSX上似乎可以工作。
以下是OSX的输出:
在Ubuntu上的输出如下:
这种情况有什么原因吗?我是否做错了什么,可能在两个不同的操作系统上处理方式不同?
为什么Ubuntu没有显示输出?
英文:
I have a go program that looks like this on Ubuntu
package main
import (
"fmt"
"time"
)
func main() {
count := 2
for i := 0; i < count; i++ {
go ping()
}
for {}
}
func ping() {
for {
time.Sleep(time.Second )
fmt.Println("hello world")
}
}
The idea was to call the go routine twice and then in each running of the go routine I would wait 1 seconds and then print "hello world"
however the output from this program on ubuntu is no output. It seems to work on OSX
here is the output from OSX:
on Ubuntu the output looks like this
Is there a reason for this madness?
Am I doing something wrong that perhaps is being handled differently on two different Operating Systems?
Why does Ubuntu show no output?
答案1
得分: 3
一个忙等待的for {}
循环不会让出给调度器,所以你的goroutine可能会或可能不会运行。这与操作系统无关;只需去掉for {}
循环即可。
英文:
A busy-wait for {}
-loop does not yield to the scheduler and so your goroutines might or might not be able to run. This has nothing to do with the OS; just get rid of the for {}
loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论