Created
January 2, 2015 14:20
-
-
Save XimingCheng/fbe54e48d12bbe4fbca5 to your computer and use it in GitHub Desktop.
A Fibonacci data cal in Golang goroutine and channel
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 shower(c chan int, quit chan bool) { | |
for { | |
select { | |
case j := <-c: | |
fmt.Printf("%v ", j) | |
case <-quit: | |
break | |
} | |
} | |
} | |
func dup3(in <-chan int) (<-chan int, <-chan int, <-chan int) { | |
a, b, c := make(chan int, 2), make(chan int, 2), make(chan int, 2) | |
go func() { | |
for { | |
println("pop x") | |
x := <-in | |
println("push a ", x) | |
a <- x | |
println("push b ", x) | |
b <- x | |
println("push out ", x) | |
c <- x | |
} | |
}() | |
return a, b, c | |
} | |
func fib() <-chan int { | |
x := make(chan int, 2) | |
a, b, out := dup3(x) | |
go func() { | |
println("push x 0") | |
x <- 0 | |
println("push x 1") | |
x <- 1 | |
println("pop a") | |
<-a | |
for { | |
println("get a + b then push x ") | |
x <- <-a + <-b | |
} | |
}() | |
return out | |
} | |
func main() { | |
// ch := make(chan int) | |
// quit := make(chan bool) | |
// go shower(ch, quit) | |
// for i := 0; i < 10; i++ { | |
// ch <- i | |
// } | |
// quit <- false | |
x := fib() | |
for i := 0; i < 10; i++ { | |
println("pop out") | |
fmt.Printf("%v ", <-x) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment