I'm recently learning concurrency in golang, and I'm thinking a program with generate a series of number and then send them to three slices, concurrently. Here's the code:
func main() {
ch := make(chan int)
done := make(chan bool)
var bag1 []int
var bag2 []int
var bag3 []int
go func() {
for i := 0; i < 1000000; i++ {
ch <- i
}
close(ch)
done <- true
}()
go sendToBag(&bag1, ch)
go sendToBag(&bag2, ch)
go sendToBag(&bag3, ch)
<-done
len1 := (len(bag1))
len2 := (len(bag2))
len3 := (len(bag3))
fmt.Println("length of bag1:", len1)
fmt.Println("length of bag2:", len2)
fmt.Println("length of bag3:", len3)
fmt.Println("total length:", len1+len2+len3)
}
func sendToBag(bag *[]int, ch <-chan int) {
for n := range ch {
*bag = append(*bag, n)
}
}
which gives the output like the following:
length of bag1: 327643
length of bag2: 335630
length of bag3: 336725
total length: 999998
The total length of three slices doesn't always add up to the count of numbers which were send to them. So my question is: what caused the promblem and how to improve the code