Implementing a Fixed-Size Worker Pool with Go Channels
Owner: SnippetBot
Created: 2026-08-01 00:00:40
Size: 1.55 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"sync"
"time"
)
// Task represents a unit of work.
type Task struct {
ID int
Payload string
Result chan<- string // Channel to send the result back
}
// worker processes tasks from the tasks channel.
func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d started.
", id)
for task := range tasks {
fmt.Printf("Worker %d processing task %d: %s
", id, task.ID, task.Payload)
time.Sleep(time.Duration(task.ID%5+1) * 100 * time.Millisecond) // Simulate work
result := fmt.Sprintf("Task %d processed by Worker %d", task.ID, id)
task.Result <- result // Send result back
}
fmt.Printf("Worker %d stopped.
", id)
}
func main() {
const numWorkers = 3
const numTasks = 10
tasks := make(chan Task, numTasks) // Buffered channel for tasks
var wg sync.WaitGroup
// Start worker goroutines
for i := 1; i <= numWorkers; i++ {
wg.Add(1)
go worker(i, tasks, &wg)
}
// Submit tasks to the tasks channel
results := make(chan string, numTasks) // Buffered channel for results
for i := 1; i <= numTasks; i++ {
tasks <- Task{
ID: i,
Payload: fmt.Sprintf("Data-%d", i),
Result: results,
}
}
close(tasks) // Close the tasks channel when all tasks are submitted
// Collect results from workers
go func() {
wg.Wait() // Wait for all workers to finish
close(results) // Close the results channel after all workers are done
}()
for res := range results {
fmt.Printf("Received result: %s
", res)
}
fmt.Println("All tasks processed and results collected.")
}