c := make(chan int) go func() { time.Sleep(time.Second * 3) fmt.Println("Write:", 1) c <- 1 // 阻塞写 } () fmt.Println("Reading") fmt.Println("Read:", <- c) // 阻塞读
c := make(chan int, 3) c <- 1 // 缓冲写 c <- 2 // 缓冲写 c <- 3 // 缓冲写 fmt.Println(<- c) // 缓冲读 fmt.Println(<- c) // 缓冲读 fmt.Println(<- c) // 缓冲读
c := make(chan int) // 读超时 select { case <- c: case <-time.After(time.Second): fmt.Println("timeout") } // 写超市 select { case c <- 1: case <-time.After(time.Second): fmt.Println("timeout") }
c := make(chan int) // 非阻塞读取 select { case <- c: default: } fmt.Println("non-blocking") // 非阻塞写 select { case c <- 1: default: } fmt.Println("non-blocking")
c := make(chan int, 2) // channel只写 var cw chan<- int = c cw <- 1 cw <- 2 // channel只读 var cr <-chan int = c fmt.Println(<- cr) fmt.Println(<- cr)
for v := range c {} // channel关闭,for循环自动退出 for { v := <- c } // channel关闭,for不会退出 for { v, isClose := <- c } // dotcoo关闭,需要手动判断退出for循环
c := make(chan int) close(c) v, isClose := <- c
提示
我已安装了开发者头条 App,不再显示该广告