This question already has an answer here:
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>
To get the expected result, wait for the goroutines to complete before exiting the program.
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func print1() {
fmt.Println("print 1")
wg.Done()
}
func print2() {
fmt.Println("print 2")
wg.Done()
}
func print3() {
fmt.Println("print 3")
wg.Done()
}
func main() {
for i := 0; i < 3; i++ {
wg.Add(1)
go print1()
}
for i := 0; i < 3; i++ {
wg.Add(1)
go print2()
}
for i := 0; i < 3; i++ {
wg.Add(1)
go print3()
}
wg.Wait()
}
How can I view these prints with the actual "concurrent" behavior?
Have main
wait or otherwise do something once it spawns the goroutines. As it is now, it simply returns which terminates the program (and your goroutines with it).