Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "time"
- )
- func main() {
- //create channels
- intchan := make(chan int)
- floatchan1 := make(chan float64)
- floatchan2 := make(chan float64)
- //launch go rountines
- go fib(intchan)
- go ratio(floatchan1, floatchan2)
- //initialize the process; pretty much fib(50)
- intchan <- 50
- //print each number from fib() and ratio()
- for i := 0; i < 50; i++ {
- fibnum := <-intchan
- floatchan1 <- float64(fibnum)
- //floatchan2 doesn't have any values in it; waiting
- //for at least two values from floatchan1 in ratio()!
- ratio := <-floatchan2
- fmt.Println(fibnum, " - ", ratio)
- time.Sleep(time.Millisecond * 250)
- }
- }
- //Pretty standard fib() function
- func fib(intchan chan int) {
- var next, current, last int
- length := <-intchan
- for i := 0; i < length; i++ {
- if current == 0 {
- next = 1
- } else {
- next = current + last
- }
- last = current
- current = next
- //put fib() result to channel
- intchan <- next
- }
- }
- func ratio(floatchan1 chan float64, floatchan2 chan float64) {
- var ratio float64
- //get two consecutive values
- x := <-floatchan1
- y := <-floatchan1
- //ratio approches golden ratio as loop goes on
- ratio = x / y
- //put ratio() result to channel to be printed in main()
- floatchan2 <- ratio
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement