duandaoji3992 2015-06-25 04:19
浏览 84
已采纳

Golang:为什么“ hello”一词会循环5次而“ world”一词只会循环4次? [重复]

This question already has an answer here:

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?

</div>
  • 写回答

1条回答 默认 最新

  • dppn67180 2015-06-25 04:54
    关注

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?