Created
November 23, 2019 19:36
-
-
Save merwane/7e5b079b800c57376736dddff5ff3dca to your computer and use it in GitHub Desktop.
Concurrent Fibonacci sequence calculation w/ Golang
This file contains 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" | |
"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