I have the following code which has a double-go routine structure:
package main
import(
"fmt"
"math/rand"
"time"
"strconv"
)
func main(){
outchan := make(chan string)
for i:=0;i<10;i++{
go testfun(i, outchan)
}
for i:=0;i<10;i++{
a := <-outchan
fmt.Println(a)
}
}
func testfun(i int, outchan chan<- string){
outchan2 := make(chan int)
time.Sleep(time.Millisecond*time.Duration(int64(rand.Intn(10))))
for j:=0;j<10;j++ {
go testfun2(j, outchan2)
}
tempStr := strconv.FormatInt(int64(i),10)+" - "
for j:=0;j<10;j++ {
tempStr = tempStr + strconv.FormatInt(int64(<-outchan2),10)
}
outchan <- tempStr
}
func testfun2(j int, outchan2 chan<- int){
time.Sleep(time.Millisecond*time.Duration(int64(rand.Intn(10))))
outchan2 <- j
}
The output I was expecting is
0 - 0123456789
1 - 0123456789
2 - 0123456789
3 - 0123456789
4 - 0123456789
5 - 0123456789
6 - 0123456789
7 - 0123456789
8 - 0123456789
9 - 0123456789
But instead I got this:
7 - 7980345261
6 - 4035897621
3 - 9047526831
9 - 4032861975
8 - 9570831624
5 - 3798021546
1 - 0985362471
0 - 1849276035
2 - 9572806143
4 - 5768032419
Could anyone show me how to achieve the output I was expecting? I'm a newbie and please forgive me if the solution is obvious. I've been looking for it for days.