Order in channels

I don’t understand why I cannot read from channels in any order I would like to. I’ve already sent values to the channels. Why should I keep the same order? Thanks :slight_smile:

 func main() {
    	ch1 := make(chan int)
    	ch2 := make(chan int)

    	go send(ch1, ch2)
    	
    	// this order DOES work
    	fmt.Println(<- ch1)
    	fmt.Println(<- ch2)
    	
    	// this order DOESN'T work
    	fmt.Println(<- ch1)
    	fmt.Println(<- ch1)
    }

    func send(ch1, ch2 chan<- int) {
    	for i := 0; i <= 10; i++ {
    		if i % 2 == 0 {
    			ch1 <- i
    		} else {
    			ch2 <- i
    		}
    	}
    	close(ch1)
    	close(ch2)
    }

You can read them in any order, though you are using unbuffered channels, this means that your “send” go routine will “sleep” until you have read the value from that channel.

If you use a buffered channel it will work better.

1 Like

But why I cannot read the values from the first channel and then start reading from a second? Why should I keep an order? I am still confused a bit…

You can read in any order, though to be able to read from a channel you need to write to it.

Currently you have a go routine that writes to one of 2 channels. As those channels are unbuffered, that go routine will not write to the other channel before the current git read.

As you try to read from the channel first that has not been written to, the reader will block as well until data is on the channel.

The scheduler recognizes that there are 2 goroutines which both are waiting for getting unblocked. The scheduler cancels the program as it knows that neither of the go routines demand can be fulfilled.

1 Like

It makes sense! Thank you!