Compare commits
No commits in common. "a54ddfe5f3d0c83b1fdafdfa0cdbdc741794e9b6" and "ef722eec2f9ae4caa2d12083f5300e383252e977" have entirely different histories.
a54ddfe5f3
...
ef722eec2f
1 changed files with 0 additions and 72 deletions
|
@ -1,72 +0,0 @@
|
||||||
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")
|
|
||||||
}
|
|
Loading…
Reference in a new issue