为什么在Ubuntu上无限循环的go例程之后,线程无法打印输出?

huangapple go评论135阅读模式
英文:

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上无限循环的go例程之后,线程无法打印输出?

在Ubuntu上的输出如下:

为什么在Ubuntu上无限循环的go例程之后,线程无法打印输出?

这种情况有什么原因吗?我是否做错了什么,可能在两个不同的操作系统上处理方式不同?

为什么Ubuntu没有显示输出?

英文:

I have a go program that looks like this on Ubuntu

package main

import (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {

	count := 2

	for i := 0; i &lt; count; i++ {

		go  ping()
	}

	for  {}
}

func ping() {

	for {
		time.Sleep(time.Second )
		fmt.Println(&quot;hello world&quot;)

	}
}

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 &quot;hello world&quot; however the output from this program on ubuntu is no output. It seems to work on OSX

here is the output from OSX:

为什么在Ubuntu上无限循环的go例程之后,线程无法打印输出?

on Ubuntu the output looks like this

为什么在Ubuntu上无限循环的go例程之后,线程无法打印输出?

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.

huangapple
  • 本文由 发表于 2016年9月6日 11:28:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/39340219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定