Skip to content

Instantly share code, notes, and snippets.

@merwane merwane/fibonacci.go
Created Nov 23, 2019

Embed
What would you like to do?
Concurrent Fibonacci sequence calculation w/ Golang
package main
import(
"fmt"
"time"
)
func main(){
defer elapsed()()
jobs := make(chan int, 100)
results := make(chan int, 100)
// concurrent workers
// remove or add some to test different configs
go worker(jobs, results)
go worker(jobs, results)
go worker(jobs, results)
go worker(jobs, results)
for i := 0; i < 100; i++ {
jobs <- i
}
close(jobs)
for j := 0; j < 50; j++ {
fmt.Println(<-results)
}
}
func worker(jobs <-chan int, results chan<- int){
for n := range jobs {
results <- fib(n)
}
}
func fib(n int) int {
if n <= 1 {
return n
}
return fib(n-1) + fib(n-2)
}
// calculate time elapsed
func elapsed() func(){
start := time.Now()
return func(){
fmt.Printf("Calculation took %v\n", time.Since(start))
}
}
// Happy Fibonacci day :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.