Skip to content

Instantly share code, notes, and snippets.

@rnemeth90
Created July 24, 2022 10:00
Show Gist options
  • Save rnemeth90/9133a73a02e34140ca76aef757de2c3b to your computer and use it in GitHub Desktop.
Save rnemeth90/9133a73a02e34140ca76aef757de2c3b to your computer and use it in GitHub Desktop.
Go Concurrent Fibonacci Calculator
package main
import (
"fmt"
"math/rand"
"time"
)
func fib(ch chan string, number float64) {
x, y := 1.0, 1.0
for i := 0; i < int(number); i++ {
x, y = y, x+y
}
r := rand.Intn(3)
time.Sleep(time.Duration(r) * time.Second)
ch <- fmt.Sprintf("Fib(%v): %v\n", number, x)
}
func main() {
start := time.Now()
size := 15
ch := make(chan string, size)
for i := 0; i < size; i++ {
go fib(ch, float64(i))
}
for i := 0; i < size; i++ {
fmt.Printf(<-ch)
}
elapsed := time.Since(start)
fmt.Printf("Done! It took %v seconds!\n", elapsed.Seconds())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment