Created
September 4, 2024 12:31
-
-
Save pedrobertao/1758b489674dd9a72096adcbfe0893f4 to your computer and use it in GitHub Desktop.
fib with go routines
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" | |
"sync" | |
) | |
var wg sync.WaitGroup | |
func readFib(c <-chan int) { | |
// Option 1 | |
// for val := range c { | |
// fmt.Println(val) | |
// } | |
// Option 2 | |
for { | |
var val int | |
var ok bool | |
if val, ok = <-c; !ok { | |
break | |
} | |
fmt.Println(val) | |
} | |
} | |
func fib(c chan<- int, n int) { | |
fibArr := []int{1, 1} | |
c <- fibArr[0] | |
c <- fibArr[1] | |
wg.Add(-2) | |
next := 0 | |
for i := 2; i < n; i++ { | |
defer wg.Done() | |
next = fibArr[i-1] + fibArr[i-2] | |
fibArr = append(fibArr, next) | |
c <- next | |
} | |
close(c) | |
} | |
func routineFib(n int) { | |
wg.Add(n) | |
ch := make(chan int, n) | |
go fib(ch, n) | |
readFib(ch) | |
wg.Wait() | |
} | |
func main() { | |
routineFib(10) | |
} | |
/* Response | |
1 | |
1 | |
2 | |
3 | |
5 | |
8 | |
13 | |
21 | |
34 | |
55 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment