Created
November 28, 2023 10:24
-
-
Save yumed15/2dd1bbd0e6137e38447183a567cc1500 to your computer and use it in GitHub Desktop.
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" | |
"sync" | |
"time" | |
) | |
type Task struct { | |
ID int | |
Weight int | |
} | |
func main() { | |
const concurrencyLimit = 10 | |
var wg sync.WaitGroup | |
tasks := make(chan Task, 20) | |
// Start worker pool | |
for i := 1; i <= concurrencyLimit; i++ { | |
go worker(i, tasks, &wg) | |
} | |
// Submit tasks with weights | |
for i := 1; i <= 20; i++ { | |
weight := i % 5 + 1 // Assign weights based on task ID (for illustration) | |
tasks <- Task{ID: i, Weight: weight} | |
} | |
close(tasks) // Close the channel to signal workers to stop | |
wg.Wait() | |
} | |
func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) { | |
defer wg.Done() | |
for task := range tasks { | |
fmt.Printf("Worker %d processing Task %d with Weight %d\n", id, task.ID, task.Weight) | |
processTask(task) | |
} | |
} | |
func processTask(task Task) { | |
// Simulate processing time based on the task's weight | |
time.Sleep(time.Duration(task.Weight) * time.Second) | |
fmt.Printf("Task %d processed\n", task.ID) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment