Golang:为什么单词 "hello" 循环 5 次而单词 "world" 只循环 4 次?
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"。
有没有人可以解释一下代码的执行顺序是什么?
程序可能在最后一个世界打印出来之前终止。 – 大卫·施瓦茨
Go 程序不会等到所有 goroutine 完成后再退出。如果你想等待 "world"s 完成打印,你可以使用 WaitGroup.
例如
将 "sync" 添加到您的导入中,并调用它:
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
say("world")
}()
say("hello")
wg.Wait()
}
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"。
有没有人可以解释一下代码的执行顺序是什么?
程序可能在最后一个世界打印出来之前终止。 – 大卫·施瓦茨
Go 程序不会等到所有 goroutine 完成后再退出。如果你想等待 "world"s 完成打印,你可以使用 WaitGroup.
例如
将 "sync" 添加到您的导入中,并调用它:
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
say("world")
}()
say("hello")
wg.Wait()
}