When your main() function terminates, your program ends. This does not wait for the completion of other larynxes.
Quote from Go Language Specification: Running a program :
Program execution begins with initializing the main package and then calling the main function. When this function returns, the program exits. It does not wait for the completion of other (not main ) goroutines.
See this answer for more details.
You must tell your main() function that the SayHello() function will start as goroutine to complete. You can synchronize them with channels, for example:
func SayHello(done chan int) { for i := 0; i < 10; i++ { fmt.Print(i, " ") } if done != nil { done <- 0 // Signal that we're done } } func main() { SayHello(nil) // Passing nil: we don't want notification here done := make(chan int) go SayHello(done) <-done // Wait until done signal arrives }
Another alternative is the completion alarm, closing the channel:
func SayHello(done chan struct{}) { for i := 0; i < 10; i++ { fmt.Print(i, " ") } if done != nil { close(done) // Signal that we're done } } func main() { SayHello(nil) // Passing nil: we don't want notification here done := make(chan struct{}) go SayHello(done) <-done // A receive from a closed channel returns the zero value immediately }
Notes:
According to your changes / comments: if you want the 2 executed SayHello() functions to print “mixed” numbers randomly: you have no guarantee to observe this behavior. Again, see the above answer for more details. The Go memory model ensures that certain events happen before other events, you have no guarantee how 2 parallel goroutines are executed.
You can experiment with it, but you know that the result will not be deterministic. First you must enable the execution of several active goroutines with:
runtime.GOMAXPROCS(2)
And secondly, you must first run SayHello() as a goroutine, because your current code first executes SayHello() in the main goroutine, and only after it finishes, run another:
runtime.GOMAXPROCS(2) done := make(chan struct{}) go SayHello(done) // FIRST START goroutine SayHello(nil) // And then call SayHello() in the main goroutine <-done // Wait for completion