Home>Article>Backend Development> About typical usage of golang select

About typical usage of golang select

藏色散人
藏色散人 forward
2021-05-08 11:56:26 1914browse

The following is the tutorial column ofgolangto introduce you to the typical usage of golang select. I hope it will be helpful to friends in need!

About typical usage of golang select

##code

package main import ( "fmt" "time" ) func chanTest(ch chan int) { for { //select外层需要循环 select { case value, ok := <-ch: fmt.Println(value, ok, time.Now()) if ok == false { fmt.Println("chan已经关闭", time.Now()) //select要自己判断退出,如果是for..range 形式,在读取完了关闭的chanel后,退出循环 return } default: fmt.Println("chan 空了", time.Now()) time.Sleep(time.Second * 5) //分支的处理会阻塞整个select } } } func main() { var ch = make(chan int, 100) go chanTest(ch) ch <- 1 ch <- 2 time.Sleep(time.Second * 2) ch <- 3 ch <- 4 time.Sleep(time.Second) close(ch) for { time.Sleep(time.Second) } }

It should be noted that select The defalut will discard the data. When the chan is full, the data entering the chan will be discarded

The above is the detailed content of About typical usage of golang select. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete