Created
July 24, 2022 10:00
-
-
Save rnemeth90/9133a73a02e34140ca76aef757de2c3b to your computer and use it in GitHub Desktop.
Go Concurrent Fibonacci Calculator
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" | |
"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