Golang:为什么单词“hello”循环5次,而单词“world”只循环4次?

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

Golang: why does the word "hello" loop 5 times while the word "world" loops only 4?

问题

以下是代码的中文翻译:

package main

import (
	"fmt"
	"time"
)

func say(s string) {
	for i := 0; i < 5; i++ {
		time.Sleep(1000 * time.Millisecond)
		fmt.Println(s)
	}
}

func main() {
	go say("world")
	say("hello")
}

运行该代码,输出结果为:

hello
world
hello
world
hello
world
hello
world
hello

在前4个循环中,每隔100毫秒,都会先打印一个"hello",然后打印一个"world"。在最后一个循环中,只会打印一个"hello"。

有人可以解释一下这段代码的执行顺序吗?

英文:
package main

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

func say(s string) {
	for i := 0; i &lt; 5; i++ {
		time.Sleep(1000 * time.Millisecond)
		fmt.Println(s)
	}
}

func main() {
	go say(&quot;world&quot;)
	say(&quot;hello&quot;)
}

Run the code, the output is:

hello
world
hello
world
hello
world
hello
world
hello

In first 4 loops,every 100ms, a "hello" will be printed followed by a "world". and only a "hello" will be printed in the last loop.

Is there anybody can explain What's the execution sequence of the code?

答案1

得分: 1

可能是程序在最后一个单词打印之前终止了。- David Schwartz

Go程序在退出之前不会等待所有goroutine完成。如果你想等待所有的"world"打印完成,你可以使用WaitGroup

例如:

在你的导入中添加"sync",并使用以下代码调用它:

func main() {
    var wg sync.WaitGroup    
    wg.Add(1)
    go func() {
        defer wg.Done()
        say("world")
    }()
    say("hello")
    wg.Wait()
}
英文:

Likely the program terminates before the last world gets printed. – David Schwartz

Go programs don't wait for all goroutines to finish before exiting. If you want to wait for the "world"s to finish printing, you can use a WaitGroup.

e.g.

Add "sync" to your imports, and call it with:

func main() {
    var wg sync.WaitGroup    
    wg.Add(1)
    go func() {
        defer wg.Done()
        say(&quot;world&quot;)
    }()
    say(&quot;hello&quot;)
    wg.Wait()
}

huangapple
  • 本文由 发表于 2015年6月25日 12:19:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/31041133.html
匿名

发表评论

匿名网友

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

确定