Go:Select语义介绍和使用

1.多channel场景

              多个channel同时需要读取或写入,怎么办?  串行操作? NO

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)
    s1 := <-output1
    fmt.Println(s1)
    s2 := <-output2
    fmt.Println(s2)
}

2.Select登场

              A. 同时监听一个或多个channel,直到其中一个channel ready

              B. 如果其中多个channel同时ready,随机选择一个进行操作。

              C. 语法和switch case有点类似,代码可读性更好。

select {
    case s1 := <-output1:
    fmt.Println(s1)
    case s2 := <-output2:
    fmt.Println(s2)
}
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)
    }
}

3.default分支,当case分支的channel都没有ready的话,执行default

              A. 用来判断channel是否满了

              B. 用来判断channel是否是空的

4. select case分支随机策略验证

package main
import (
    "fmt"
    "time"
)
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)
    }
}

5. empty select

package main
func main() {
    select {
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值