1
0
Fork 0
Learning-GoLang/multi-threading/fibonacci-multi-threaded.go

71 lines
1.5 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"math/rand"
"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
// Max and Min Fibonacci numbers
const maxFib = 50
const minFib = 5
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
// 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
2024-07-18 23:25:52 +02:00
for i := 1; i <= numTasks; i++ {
n := rand.Intn(maxFib - minFib) // Random number between minFib and maxFib
tasks <- Task{id: i, n: n}
2024-07-18 23:25:52 +02:00
}
// Close the task channel to signal no more tasks
close(tasks)
// Wait for all workers to finish
wg.Wait()
fmt.Println("All tasks processed")
}