简单并发[重复]

简单并发[重复]

问题描述:

This question already has an answer here:

Can someone explain how this works:

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    say("world")
}

But this doesnt work once i add the word go to the routine in main

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
}

I think its because its finishing before executing the goroutine.

</div>

The "world" goroutine does not run or complete because main returns and the program exits.

When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete. https://golang.org/ref/spec#Program_execution