I get user input number and then run a number of goroutines equals to entered number. That’s seems ok, but sometimes I get unexpected result, when the number of started routines is less than entered number.
fmt.Println("Enter number from 2 to 13")
var num int
//accepts only 2-13
for {
in := bufio.NewScanner(os.Stdin)
in.Scan()
num, _ = strconv.Atoi(in.Text())
if num >= minRoutinesNumber && num <= maxRoutinesNumber {
break
}
}
fmt.Println("num =", num)
routines := []Player{}
for i := 1; i <= num; i++ {
go func(i int) {
//fmt.Println("goroutine index", i)
routines = append(routines, Player{name: "", id: i})
}(i)
}
time.Sleep(1 * time.Second)
fmt.Println("players rotines lengts", len(routines))
for _, r := range routines {
fmt.Println("player.id:", r.id)
}
Sometimes I get unexpected number of routines, why?
For instance, last time I entered 5 and I got players rotines lengts 2
- there is something wrong…
andy@sol:~/go/src/cities$ go run main.go
Enter number from 2 to 13
7
num = 7
players rotines lengts 7
player.id: 5
player.id: 6
player.id: 7
player.id: 2
player.id: 1
player.id: 3
player.id: 4
andy@sol:~/go/src/cities$ go run main.go
Enter number from 2 to 13
8
num = 8
players rotines lengts 8
player.id: 4
player.id: 1
player.id: 2
player.id: 3
player.id: 6
player.id: 5
player.id: 7
player.id: 8
andy@sol:~/go/src/cities$ go run main.go
Enter number from 2 to 13
5
num = 5
players rotines lengts 2 // !!!!!!!!!
player.id: 2
player.id: 1
andy@sol:~/go/src/cities$