Skip to content

Instantly share code, notes, and snippets.

@merwane
Created November 23, 2019 19:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merwane/7e5b079b800c57376736dddff5ff3dca to your computer and use it in GitHub Desktop.
Save merwane/7e5b079b800c57376736dddff5ff3dca to your computer and use it in GitHub Desktop.
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