Golang channel output order

前端 未结 4 801
说谎
说谎 2020-12-11 11:06
func main() {
  messages := make(chan string)
  go func() { messages <- \"hello\" }()
  go func() { messages <- \"ping\" }()
  msg := <-messages
  msg2 := &         


        
4条回答
  •  长情又很酷
    2020-12-11 11:38

    I was confused when I first met this. but now I am clear about this. the reason cause this is not about channel, but for goroutine.

    As The Go Memory Model mention, there's no guaranteed to goroutine's running and exit, so when you create two goroutine, you cannot make sure that they are running in order.

    So if you want printing follow FIFO rule, you can change your code like this:

    func main() {
        messages := make(chan string)
        go func() {
            messages <- "hello"
            messages <- "ping"
        }()
        //go func() { messages <- "ping" }()
        msg := <-messages
        msg2 := <-messages
        fmt.Println(msg)
        fmt.Println(msg2)
    }
    

提交回复
热议问题