Sveargith
Sveargith

Reputation: 429

Sending data to two channels, the second channel might receive data first sometime

package main

func m() {
    c1 := make(chan int, 1)
    c2 := make(chan int, 1)
    go func() {
        c1 <- 1
        c2 <- 1
    }()
    select {
    case <-c1:
    case <-c2:
        println("no way")
    }
}

func main() {
    for i := 0; i < 1000000; i++ {
        m()
    }
}

There are two channels c1, c2.

We are sending data to c1 and c2 in a goroutine. And we have a select to receive the data from these two channels and return.

The question is: we are send data to c1 first and receive from c1 first in most cases. But sometimes we receive from c2 first when sending to c1 first. Why?

Upvotes: 1

Views: 61

Answers (1)

Related Questions