简体   繁体   中英

Select in channel

The following is one example code for select. I don't understand why the second select doesn't execute the first case? The output seems to be:

messages := make(chan string)
signals := make(chan bool)

// Here's a non-blocking receive. If a value is
// available on `messages` then `select` will take
// the `<-messages` `case` with that value. If not
// it will immediately take the `default` case.
select {
case msg := <-messages:
    fmt.Println("received message", msg)
default:
    fmt.Println("no message received")
}

// A non-blocking send works similarly.
msg := "hi"
select {
case messages <- msg:
    fmt.Println("sent message", msg)
default:
    fmt.Println("no message sent")
}

// We can use multiple `case`s above the `default`
// clause to implement a multi-way non-blocking
// select. Here we attempt non-blocking receives
// on both `messages` and `signals`.
select {
case msg := <-messages:
    fmt.Println("received message", msg)
case sig := <-signals:
    fmt.Println("received signal", sig)
default:
    fmt.Println("no activity")
}

After I run the code, the output:

no message received
no message sent
no activity

Updated: I know why the second select goes to default now. What about the third one?

messages is unbuffered, and no other Go routine is blocked waiting for something to be received. Since the send operation will block, the default case is executed.

Compare this to the behaviour of a buffered channel or when another Go routine is blocked reading on the channel .

From the language specification :

  1. If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM