-1
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?

kristianp
  • 5,496
  • 37
  • 56
Snowwolf
  • 138
  • 2
  • 11
  • 1
    Likely the program terminates before the last `world` gets printed. – David Schwartz Jun 25 '15 at 04:21
  • What @DavidSchwartz points out is likely correct, can you add a 2 second sleep to the end of the main method and report the result? – moreON Jun 25 '15 at 04:41
  • 1
    Also related: [Goroutine does not execute if time.Sleep included](http://stackoverflow.com/questions/28307783/goroutine-does-not-execute-if-time-sleep-included) – icza Jun 25 '15 at 05:28
  • Considering this exact example came up before, where is its source? Maybe there is a bug in the source documentation we can report. – Frederick F. Kautz IV Jun 25 '15 at 17:48

1 Answers1

1

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()
}
kristianp
  • 5,496
  • 37
  • 56