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

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

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函数同时运行。

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

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

  1. func getHostName(h chan string, ipAdresse string, n int) {
  2. //这里!!!
  3. time.Sleep(4 * time.Second)
  4. ip := ipAdresse + strconv.Itoa(n)
  5. //ip, ok := net.LookupAddr(ip)
  6. if false {
  7. h <- ip + " - "
  8. } else {
  9. h <- "error" + strconv.Itoa(n)
  10. }
  11. }

所以它们都同时完成。

英文:

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.

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

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

  1. func getHostName(h chan string, ipAdresse string, n int) {
  2. //Here!!!
  3. time.Sleep(4 * time.Second)
  4. ip := ipAdresse + strconv.Itoa(n)
  5. //ip, ok := net.LookupAddr(ip)
  6. if false {
  7. h &lt;- ip + &quot; - &quot;
  8. } else {
  9. h &lt;- &quot;error&quot; + strconv.Itoa(n)
  10. }
  11. }

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:

确定