package main import "fmt" func fibonacci(ch chan <- int, quit <- chan bool) { x, y := 1, 1 for true { 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<8; i++ { num := <-ch fmt.Println("num = ",num) } quit <- true //可以退出,即给quit赋了一个值,之前都是一直在阻塞 }() fibonacci(ch, quit) }
执行的结果
num = 1 num = 1 num = 2 num = 3 num = 5 num = 8 num = 13 num = 21 flag = true