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

927 views Asked by At
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

There are 1 answers

0
kristianp On BEST ANSWER

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()
}