Select多路复用
生活随笔
收集整理的這篇文章主要介紹了
Select多路复用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在某些場(chǎng)景下我們需要同時(shí)從多個(gè)通道接收數(shù)據(jù)。通道在接收數(shù)據(jù)時(shí),如果沒有數(shù)據(jù)可以接收將會(huì)發(fā)生阻塞,而select就可以同時(shí)監(jiān)聽一個(gè)或多個(gè)channel,直到其中一個(gè)channel準(zhǔn)備好。
select的使用類似于switch語句,它有一系列case分支和一個(gè)默認(rèn)的分支。每個(gè)case會(huì)對(duì)應(yīng)一個(gè)通道的通信(接收或發(fā)送)過程。select會(huì)一直等待,直到某個(gè)case的通信操作完成時(shí),就會(huì)執(zhí)行case分支對(duì)應(yīng)的語句。具體格式如下:
select {case <-chan1:// 如果chan1成功讀到數(shù)據(jù),則進(jìn)行該case處理語句case chan2 <- 1:// 如果成功向chan2寫入數(shù)據(jù),則進(jìn)行該case處理語句default:// 如果上面都沒有成功,則進(jìn)入default處理流程} package mainimport ("fmt""time" )func test1(ch chan string) {time.Sleep(time.Second * 1)ch <- "test1" } func test2(ch chan string) {time.Sleep(time.Second * 2)ch <- "test2" }func main() {// 2個(gè)管道output1 := make(chan string)output2 := make(chan string)// 跑2個(gè)子協(xié)程,寫數(shù)據(jù)go test1(output1)go test2(output2)for {// 用select監(jiān)控select {case s1 := <-output1:fmt.Println("s1=", s1)case s2 := <-output2:fmt.Println("s2=", s2)default:ticker := time.NewTicker(1 * time.Second)fmt.Printf("%v\n", <-ticker.C)}} }判斷通道是否已經(jīng)存滿
package mainimport ("fmt""time" )// 判斷管道有沒有存滿 func main() {// 創(chuàng)建管道output1 := make(chan string, 1)// 子協(xié)程寫數(shù)據(jù)go write(output1)// 取數(shù)據(jù)for s := range output1 {fmt.Println("res:", s)time.Sleep(time.Second)} }func write(ch chan string) {for {select {// 寫數(shù)據(jù)case ch <- "hello":fmt.Println("write hello")default:fmt.Println("channel full")}time.Sleep(time.Millisecond * 500)} }總結(jié)
以上是生活随笔為你收集整理的Select多路复用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Goroutine池
- 下一篇: 定时器Timer和Ticker