并行化 – 为什么sleep只暂停一次?

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

Parallelisation - Why does sleep pause only once?

问题

为什么只等待第一个goroutine,而其他的则直接执行。我认为这是因为通道c chan string,但我不理解两者之间的行为。

英文:

Why do wait only the first goroutine with

func Sleep(d Duration)
http://golang.org/pkg/time
"Sleep pauses the current goroutine for the duration d."

but the rest is execute directly. I think cause the channel c chan string but i dont understand the behaviour between both.

My Example GoPlayground

答案1

得分: 4

你的所有go例程都是并发运行的,所以它们都同时休眠4秒钟,因此它们同时结束。

你像这样调用它们。go意味着所有的getHostName函数同时运行。

for i := 0; i < max; i++ {
	go getHostName(haveHost, ipadresse_3, i)
}

这意味着所有的休眠同时发生。

func getHostName(h chan string, ipAdresse string, n int) {
	
	//这里!!!
	time.Sleep(4 * time.Second)
	ip := ipAdresse + strconv.Itoa(n)

	//ip, ok := net.LookupAddr(ip)

	if false {
		h <- ip + " - "
	} else {
		h <- "error" + strconv.Itoa(n)	
	}
}

所以它们都同时完成。

英文:

All your go routines are running concurrently so they all sleep for 4 seconds at the same time, hence they all end at the same time.

You called them like this. The go means that all the getHostName functions run at once.

for i := 0; i &lt; max; i++ {
	go getHostName(haveHost, ipadresse_3, i)
}

And this means that all the sleeps happen at the same time

func getHostName(h chan string, ipAdresse string, n int) {
	
	//Here!!!
	time.Sleep(4 * time.Second)
	ip := ipAdresse + strconv.Itoa(n)

	//ip, ok := net.LookupAddr(ip)

	if false {
		h &lt;- ip + &quot; - &quot;
	} else {
		h &lt;- &quot;error&quot; + strconv.Itoa(n)	
	}
}

So they all finish at the same time.

huangapple
  • 本文由 发表于 2012年12月13日 06:16:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/13849649.html
匿名

发表评论

匿名网友

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

确定