Go 经典入门系列 24: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)
    go server1(output1)
    go server2(output2)
    select {
    case s1 := <-output1:
        fmt.Println(s1)
    case s2 := <-output2:
        fmt.Println(s2)
    }
}

在线运行程序[2]

在上面程序里,server1 函数(第 8 行)休眠了 6 秒,接着将文本 from server1 写入信道ch。而 server2 函数(第 12 行)休眠了 3 秒,然后把 from server2 写入了信道 ch

而 main 函数在第 20 行和第 21 行,分别调用了 server1 和 server2 两个 Go 协程。

在第 22 行,程序运行到了 select 语句。select 会一直发生阻塞,除非其中有 case 准备就绪。在上述程序里,server1 协程会在 6 秒之后写入 output1 信道,而server2 协程在 3 秒之后就写入了 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值