/ 2019-03-19
chan 选择
如果需要同时处理多个 channel,可使用 select 语句。它随机选择一个可用 channel 做收发操作,或执行 default case。
用 select 实现超时控制:
package main
import (
"fmt"
"time"
)
func main() {
exit := make(chan bool)
intChan := make(chan int, 2)
strChan := make(chan string, 2)
go func() {
select {
case vi := <-intchan:
fmt.Println(vi)
case vs := <-strchan:
fmt.Println(vs)
case <-time.After(time.Second * 3):
fmt.Println("timeout.")
}
exit <- true
}()
// intChan <- 100 // 注释掉,引发 timeout。
// strChan <- "oldboy"
<-exit
}
在循环中使用 select default case 需要小心,避免形成洪水。
简单工厂模式
用简单工厂模式打包并发任务和 channel。
package main
import (
"fmt"
"math/rand"
"time"
)
func NewTest() chan int {
c := make(chan int)
rand.Seed(time.Now().UnixNano())
go func() {
time.Sleep(time.Second)
c <- rand.Int()
}()
return c
}
func main() {
t := NewTest()
fmt.Println(<-t) // 等待 goroutine 结束返回。
}
(2)