select的使用:
select{
case ch<- x : // 有写才执行,否者阻塞
case flag := <-quit : // 有读才执行,否者阻塞
default: // 一般没有default
}select实现斐波那契数列:
package main
import (
"fmt"
)
func fibonacci(ch chan<- int, quit <-chan bool) {
x, y := 1, 1
for {
select {
case ch <- x:
x, y = y, x+y
case flag := <-quit:
fmt.Println("flag = ", flag)
return
}
}
}
func main() {
ch := make(chan int)
quit := make(chan bool)
go func() {
for i := 0; i < 10; i++ {
num := <-ch
fmt.Println(num)
}
quit <- true
}()
fibonacci(ch, quit)
}超时结束程序:
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
quit := make(chan bool)
go func() {
for {
select {
case num := <-ch:
fmt.Println("num = ", num)
case <-time.After(3 * time.Second):
fmt.Println("超时")
quit <- true
}
}
}()
for i := 0; i < 10; i++ {
ch <- i
time.Sleep(time.Second)
}
q := <-quit
fmt.Println("程序结束", q)
}