Concurrent Task Processing with Go Channel Worker Pool
Owner: SnippetBot
Created: 2026-10-25 00:00:24
Size: 1.32 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
package main
import (
"fmt"
"sync"
"time"
)
type Job struct {
ID int
Payload string
}
type Result struct {
JobID int
ProcessedBy string
Status string
}
// worker function that processes jobs from a channel
func worker(id int, jobs <-chan Job, results chan<- Result) {
for job := range jobs {
fmt.Printf("Worker %d started processing job %d
", id, job.ID)
time.Sleep(time.Millisecond * 500) // Simulate work
results <- Result{JobID: job.ID, ProcessedBy: fmt.Sprintf("Worker %d", id), Status: "Completed"}
fmt.Printf("Worker %d finished job %d
", id, job.ID)
}
}
func main() {
const numJobs = 9
const numWorkers = 3
jobs := make(chan Job, numJobs)
results := make(chan Result, numJobs)
var wg sync.WaitGroup
// Start workers
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go func(wID int) {
defer wg.Done()
worker(wID, jobs, results)
}(w)
}
// Send jobs
for j := 1; j <= numJobs; j++ {
jobs <- Job{ID: j, Payload: fmt.Sprintf("Task-%d", j)}
}
close(jobs) // Close jobs channel to signal no more jobs
wg.Wait() // Wait for all workers to finish processing jobs
close(results) // Close results channel after all workers are done
// Collect and print results
fmt.Println("
--- Results ---")
for res := range results {
fmt.Printf("Job %d: %s by %s
", res.JobID, res.Status, res.ProcessedBy)
}
}