channel 阻塞读 channel 阻塞写
- c := make(chan int)go func() { time.Sleep(time.Second * 3) fmt.Println("Write:", 1) c <- 1 // 阻塞写} ()fmt.Println("Reading")fmt.Println("Read:", <- c) // 阻塞读
channel 缓冲读 channel 缓冲写
- c := make(chan int, 3)c <- 1 // 缓冲写c <- 2 // 缓冲写c <- 3 // 缓冲写fmt.Println(<- c) // 缓冲读fmt.Println(<- c) // 缓冲读fmt.Println(<- c) // 缓冲读
channel 非阻塞读 channel 非阻塞写
- 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")}
channel 非阻塞读 channel 非阻塞写
- c := make(chan int)// 非阻塞读取select {case <- c:default:}fmt.Println("non-blocking")// 非阻塞写select {case c <- 1:default:}fmt.Println("non-blocking")
channel 只读 channel 只写
- c := make(chan int, 2)// channel只写var cw chan<- int = ccw <- 1cw <- 2// channel只读var cr <-chan int = cfmt.Println(<- cr)fmt.Println(<- cr)
channel 读取
- for v := range c {} // channel关闭,for循环自动退出for { v := <- c } // channel关闭,for不会退出for { v, isClose := <- c } // dotcoo关闭,需要手动判断退出for循环
channel 关闭
- c := make(chan int)close(c)v, isClose := <- c
来源: http://www.92to.com/bangong/2017/08-17/27110801.html