英文:
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 (
"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")
}
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("world")
}()
say("hello")
wg.Wait()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论