An unexpected number of started routines

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$
1 Like

This is not a proper means of synchronisation, try using a sync.WaitGroup instead.

6 Likes

And you also should keep in mind that append operation is not thread-safe.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.