In the following code snippet, tasks
is a buffered channel of length 30 that is populated with exactly 30 elements. I'm writing a for
loop to operate on each task, which is read in from a channel.
for i := 0; i < len(tasks); i++ {
fmt.Println(i)
select {
case task := <-tasks:
fmt.Println(task)
// Do something
}
}
fmt.Println("Done")
However, this for loop only runs from 0 to 14. When I vary the length of this channel (which depends on the number of task elements I have), the for loop always only runs for half of len(tasks)
. Why is this the case?
Background:
I use a buffered channel for the tasks because I intend to execute each task in a goroutine, and tasks are dealt with if they fail. But I've currently cut code down to a select case in a for loop, and I'm confused about why the select case causes the for loop to only execute for half the time. I confirm that this for loop has finished executing, and that after the last execution, i
is equal to 14 (channel length is 30).