Worker Pool Over a Channel
Dispatch jobs to a fixed pool of workers through channels, bounding concurrency while processing a large queue of tasks.
Code
package main
import (
"fmt"
"sync"
)
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
results <- job * job
}
}
func runPool(items []int, workers int) []int {
jobs := make(chan int, len(items))
results := make(chan int, len(items))
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
for _, item := range items {
jobs <- item
}
close(jobs)
wg.Wait()
close(results)
out := make([]int, 0, len(items))
for result := range results {
out = append(out, result)
}
return out
}
func main() {
fmt.Println(runPool([]int{1, 2, 3, 4}, 2))
}How the snippet works
Structurally, expect the functions worker, runPool and main and nothing else.
Repetition is confined to for job := range jobs — the rest of the file is straight-line. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
Applying it
Entry signature: func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup)
Launch the file; main takes over and steps through runPool.
Statements that matter
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
results <- job * job
}
}
for result := range results {
out = append(out, result)
}
for _, item := range items {
jobs <- item
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- How do you run Worker Pool Over a Channel?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.