diff --git a/multi-threading/fibonacci-multi-threaded.go b/multi-threading/fibonacci-multi-threaded.go new file mode 100644 index 0000000..c3b86b4 --- /dev/null +++ b/multi-threading/fibonacci-multi-threaded.go @@ -0,0 +1,72 @@ +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 + for i := 1; i <= numTasks; i++ { + n := rand.Intn(maxFib - minFib) + tasks <- Task{id: i, n: 30} // n=30 is computationally intensive for Fibonacci + } + + n := rand.Intn(maxFib - minFib) // Random number between minFib and maxFib + tasks <- Task{id: i, n: n} + // Close the task channel to signal no more tasks + close(tasks) + + // Wait for all workers to finish + wg.Wait() + fmt.Println("All tasks processed") +}