While SayHello()
executes as expected, the goroutine prints nothing.
package main
import "fmt"
func SayHello() {
for i := 0; i < 10 ; i++ {
fmt.Print(i, " ")
}
}
func main() {
SayHello()
go SayHello()
}
While SayHello()
executes as expected, the goroutine prints nothing.
package main
import "fmt"
func SayHello() {
for i := 0; i < 10 ; i++ {
fmt.Print(i, " ")
}
}
func main() {
SayHello()
go SayHello()
}
When your
main()
function ends, your program ends as well. It does not wait for other goroutines to finish.Quoting from the Go Language Specification: Program Execution:
See this answer for more details.
You have to tell your
main()
function to wait for theSayHello()
function started as a goroutine to complete. You can synchronize them with channels for example:Another alternative is to signal the completion by closing the channel:
Notes:
According to your edits/comments: if you want the 2 running
SayHello()
functions to print "mixed" numbers randomly: you have no guarantee to observe such behaviour. Again, see the aforementioned answer for more details. The Go Memory Model only guarantees that certain events happen before other events, you have no guarantee how 2 concurrent goroutines are executed.You might experiment with it, but know that the result will not be deterministic. First you have to enable multiple active goroutines to be executed with:
And second you have to first start
SayHello()
as a goroutine because your current code first executesSayHello()
in the main goroutine and only once it finished starts the other one:Alternatively (to icza's answer) you can use
WaitGroup
fromsync
package and anonymous function to avoid altering originalSayHello
.In order to print numbers simultaneously run each print statement in separate routine like the following