Created
July 4, 2016 05:35
-
-
Save limboinf/30dfe3c26924f74c9d0d3ad955071947 to your computer and use it in GitHub Desktop.
go select with fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func fib(c, quit chan int) { | |
x, y := 0, 1 | |
// select 语句使得一个goroutine在多个通讯操作上等待 | |
// select 会阻塞,直到条件分支中的某个可以继续执行,如果有多个可执行,则随机执行一个 | |
for { | |
select { | |
case c <- x: | |
x, y = y, x+y | |
case <-quit: | |
fmt.Println("quit") | |
return | |
} | |
} | |
} | |
func main() { | |
c := make(chan int) | |
quit := make(chan int) | |
go func() { | |
for i := 0; i < 10; i++ { | |
fmt.Println(<-c) | |
} | |
quit <- 0 | |
}() | |
fib(c, quit) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment