Always a deadlock ! Why?

package main

import “fmt”

func main() {

c := make(chan int)

for i := 0; i < 10; i++ {

	go func() {
		for j := 0; j < 10; j++ {
			c <- j
		}
	}()

}
//Always a deadlock at the end while using range clause.
//close(c) also didn't work
for range c {
	fmt.Println(<-c)
}
// But this works fine. Why??
for k := 0; k < 100; k++ {
	fmt.Println(<-ch)
}

}

You are never closing the channel. But you need to do it from the correct location.

Where tried you before?

The for k := 0; k < 100; k++ loop runs 100 times and reads 100 values from the channel - this is okay.

The for range c loop runs endlessly and consumes all the values from the channel until all the go-routines are finished. It continues to read from the empty channel as the only routine left which raises the deadlock.

Both :

  • just before the termination of for i loop
  • just before the termination of go func()

So you are saying we can’t use range clause in this case?

Of course its possible, all you need is a sync.WaitGroup and another go-routine.

Click for spoilers

https://play.golang.org/p/6x77FRv9C-R

2 Likes

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