Getting deadlock error on debug when extracting values from channel

Short : I get a deadlock when trying to extract values from the channel.

Long:
ch1 := make(chan int, 100)

// PUT 10 values to the channel

with this:

for value := <-ch1 {
  arr = append(arr,value)
}

My program stales, or I get the deadlock error when debugging.

But with this

func ExtractChannel(ch chan int, maxSkip int) []int {
	skip := 0
	array := make([]int, 0)
	for skip < maxSkip {
		select {
		case c := <-ch:
			array = append(array, c)
		default:
			skip++
			time.Sleep(50 * time.Millisecond)
		}
	}

	return array
}

arr := ExtractChannel(ch1, 10)

All works ok.

I feel that my variation is a bit overcomplicated.

may be the purpose is that when I create a channel I put 100 capacity:

ch1 := make(chan int, 100)

But in my code it is filled only with 10 values.

Any comments about this?

For loop reading from the channel is a blocker, which exits only when the channel is closed. E.g.,

ch := make(chan int, 100)
arr := make([]int, 0, 0)

go func() {
    for i := range 10 {
        ch <- i
    }
    close(ch)
}()

for i := range ch {
    arr = append(arr, i)
}
2 Likes
  • Closing the channel is what signals the receiver that no more values are coming.
  • Buffer size (100 vs 10) doesn’t matter for correctness here, only for performance (to avoid blocking sends).
  • Using select { … default: … } is usually for non-blocking reads, not for normal draining.