This question already has an answer here:
- No output from goroutine in Go 3 answers
I can't explain the behavior of goruotines in certain cases. I try to make an easy example.
This is my own file "main.go
":
package main
import (
"fmt"
)
func print1() {
fmt.Println("print 1")
}
func print2() {
fmt.Println("print 2")
}
func print3() {
fmt.Println("print 3")
}
func main() {
for i:=0; i<3; i++ {
go print1()
}
for i:=0; i<3; i++ {
go print2()
}
for i:=0; i<3; i++ {
go print3()
}
}
I would expect the 3 functions (each invoked three times in a cycle) are performed concurrently, with the result that the order of the print numbers is unpredictable.
I can't understand why the program compiles and executes without any error but it doesn't print anything on the console!
In practice, it is as if the function calls inside the for are not executed. If I remove the go
clauses, the prints are displayed on the console. I came to the conclusion that parallel threads do not have the right to print on my console. How can I view these prints with the actual "concurrent" behavior?
</div>