利用select非阻塞接收数据
您可以使用select语句的default部分来实现非阻塞等待。
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 1)
end:
for {
select {
case n := <-ch:
fmt.Printf("Received %d from a channel\n", n)
break end
default:
fmt.Print("Channel is empty\n")
ch <- 8
}
// wait for channel to be filled with values
// don't use time.Sleep() like that in production code
time.Sleep(20 * time.Millisecond)
}
}
----------Output------------
Channel is empty
Received 8 from a channel
在第一遍for
循环迭代中,select
语句在执行到default
子句时就立即结束,因为通道是空的。
第一遍的default
子句中将8
发送到了通道,第二遍迭代时case
子句命中,然后将数据取出并中断循环。
最后更新于
这有帮助吗?