Golang channel output order

前端 未结 4 793
说谎
说谎 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:36

    In Golang Spec Channels order is described as:-

    Channels act as first-in-first-out queues. For example, if one goroutine sends values on a channel and a second goroutine receives them, the values are received in the order sent.

    It will prints which value is available first to be received on other end. If you wants to synchronize them use different channels or add wait Groups.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
      messages1 := make(chan string)
      messages2 := make(chan string)
      go func(<-chan string) {
            messages2 <- "ping" 
        }(messages2)
      go func(<-chan string) {
            messages1 <- "hello" 
        }(messages1)
      fmt.Println(<-messages1)
      fmt.Println(<-messages2)
    }
    

    If you see you can easily receive any value you want according to your choice using different channels.

    Go playground

提交回复
热议问题