1
0
Fork 0

Add: script to calculate fibonacci numbers multi threaded

This commit is contained in:
Aroy-Art 2024-07-18 23:07:46 +02:00
parent ef722eec2f
commit 13091c74a8
Signed by: Aroy
GPG key ID: 583642324A1D2070

View file

@ -0,0 +1,63 @@
package main
import (
"fmt"
"sync"
"time"
)
// Task struct representing a task to be processed
type Task struct {
id int
n int
}
// Function to calculate the nth Fibonacci number (inefficient recursive approach)
func fibonacci(n int) int {
if n <= 1 {
return n
}
return fibonacci(n-1) + fibonacci(n-2)
}
// Worker function that processes tasks from the task channel
func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) {
defer wg.Done()
for task := range tasks {
start := time.Now()
result := fibonacci(task.n)
duration := time.Since(start)
fmt.Printf("Worker %d processed task %d: Fibonacci(%d) = %d (took %s)\n",
id, task.id, task.n, result, duration)
}
}
func main() {
const numWorkers = 3
const numTasks = 10
// Create a channel to send tasks to workers
tasks := make(chan Task, numTasks)
// Create a WaitGroup to wait for all workers to finish
var wg sync.WaitGroup
// Start worker goroutines
for i := 1; i <= numWorkers; i++ {
wg.Add(1)
go worker(i, tasks, &wg)
}
// Send tasks to the task channel
for i := 1; i <= numTasks; i++ {
n := rand.Intn(maxFib - minFib)
tasks <- Task{id: i, n: 30} // n=30 is computationally intensive for Fibonacci
}
// Close the task channel to signal no more tasks
close(tasks)
// Wait for all workers to finish
wg.Wait()
fmt.Println("All tasks processed")
}