Home>Article>Backend Development> About typical usage of golang select
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!
##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) } }
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!