Golang select

Golang下select的功能和Linux IO复用中的select, poll, epoll相似,是监听 channel 操作,当 channel 操作发生时,触发相应的动作。

package main

import "time"
import "fmt"

func main() {

/* 用于做定时器 */
timeout := make(chan bool, 1)
go func() {
time.Sleep(1e9) // one second
timeout <- true
}()
ch := make(chan int)
select {
case <-ch:
case <-timeout:
fmt.Println("timeout")
}

/*当请求进来的时候我们会生成一个 job 扔进 channel, 由其他协程从 channel 中获取 job 去执行。 但是我们希望当 channel 瞒了的时候, 将该 job 抛弃并回复 【服务繁忙,请稍微再试。】 就可以用 select 实现该需求。 */
ch2 := make(chan int, 1)
ch2 <- 2
select {
case ch2 <- 3:
default:
fmt.Println("channel is full !")
}
}

posted on 2018-03-12 17:52  阳台  阅读(204)  评论(0)    收藏  举报

导航