Select

什么是 select?

select 语句用于在多个发送/接收信道操作中进行选择。select 语句会一直阻塞,直到发送/接收操作准备就绪。
如果有多个信道操作准备完毕,select 会随机地选取其中之一执行。
该语法与 switch 类似,所不同的是,这里的每个 case 语句都是信道操作。我们好好看一些代码来加深理解吧。

示例

package main

import (
    "fmt"
    "time"
)

//func server1(ch chan string) {
//    time.Sleep(6 * time.Second)
//    ch <- "from server1"
//}
//
//
//func server2(ch chan string) {
//    time.Sleep(3 * time.Second)
//    ch <- "from server2"
//
//}
//
//func main() {
//    output1 := make(chan string)
//    output2 := make(chan string)
//    //开启两个协程执行server
//    go server2(output1)
//    go server2(output2)
//    select {
//    case s1 := <-output1:
//        fmt.Println(s1,"ddddd")
//    case s2 := <-output2:
//        fmt.Println(s2,"yyyy")
//    }
//}

//func process(ch chan string) {
//    time.Sleep(10500 * time.Millisecond)
//    ch <- "process successful"
//}
//
//func main() {
//    ch := make(chan string)
//    go process(ch)
//    for {
//        time.Sleep(1000 * time.Millisecond)
//        select {
//        case v := <-ch:
//            fmt.Println("received value: ", v)
//            return
//        default:
//            // 可以干其他事,模拟非阻塞式io
//            fmt.Println("no value received")
//        }
//    }
//
//}

//死锁
//func main() {
//    ch := make(chan string)
//    select {
//    case <-ch:
//    }
//}

// 随机选取
func server1(ch chan string) {
    ch <- "from server1"
}
func server2(ch chan string) {
    ch <- "from server2"

}
func main() {
    output1 := make(chan string)
    output2 := make(chan string)
    go server1(output1)
    go server2(output2)
    time.Sleep(1 * time.Second)
    select {
    case s1 := <-output1:
        fmt.Println(s1)
    case s2 := <-output2:
        fmt.Println(s2)
    }
}
原文地址:https://www.cnblogs.com/ZhZhang12138/p/14886772.html