Golang非阻塞channel

2016-10-19 11:14  2348人阅读  评论 (0)
Tags: golang

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 = c
cw <- 1
cw <- 2
// channel只读
var cr <-chan int = c
fmt.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