关于golang:Go-select语句详解

5次阅读

共计 688 个字符,预计需要花费 2 分钟才能阅读完成。

    select 是 Go 提供的一个抉择语句,通过 select 能够监听 chanel 上的数据流动。
    select 语句的应用办法和 switch 语句类似,由 select 开始一个新的抉择块,每一个抉择块,每一个抉择条件由 case 语句来实现。
    和 switch 语句不同的中央在于,select 的 case 条件都是 chanel 的通信操作,select 语句依据不同的 case 有可能被阻塞,也可能被执行。

举个例子:

package main

import (
    "fmt"
    "time"
)

func main() {ch1 := make(chan int)
    ch2 := make(chan int)

    go func() {time.Sleep(3 * time.Second)
        ch1 <- 100
    }()
    go func() {time.Sleep(3 * time.Second)
        ch2 <- 100
    }()

    select {
    case num1 := <-ch1:
        fmt.Println("ch1 中获取的数据:", num1)
    case num2, ok := <-ch2:
        if ok {fmt.Println("ch2 中读取的数据:", num2)
        } else {fmt.Println("ch2 已敞开")
        }
    //default:
    //     fmt.Println("default 语句可选 可有可无")
    }
    fmt.Println("main goroutine has been completed")
}

这里因为 ch1 和 ch2 都写入了数据,select 会随机抉择一个 case 执行,有 default 语句就执行 default 语句,都没有的话就阻塞直到有满足条件的 case 呈现。

参考:bilibili

正文完
 0