Bounded Concurrency Worker Pool
Cap in-flight work with a semaphore channel so a large batch never opens more connections than the upstream tolerates.
Code
package main
import (
"fmt"
"sync"
)
func process(id int) string {
return fmt.Sprintf("done-%d", id)
}
func main() {
const workers = 3
jobs := make(chan int)
results := make(chan string)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
// 固定数量的 worker 消费:在飞任务数天然受限于 workers
for id := range jobs {
results <- process(id)
}
}()
}
go func() {
for i := 1; i <= 9; i++ {
jobs <- i
}
close(jobs)
}()
go func() {
wg.Wait()
close(results)
}()
count := 0
for range results {
count++
}
fmt.Println("processed:", count, "with", workers, "workers")
}How it works
One way to read it: the functions process and main, doing all the work.
The one repetition in this snippet is the loop for w := 0; w < workers; w++. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Applying it
Entry signature: func process(id int) string
Look for the processed: prefixes when the file runs; they tie each line to its step.
Running the file executes main, which drives process in order.
Statements that matter
return fmt.Sprintf("done-%d", id)
for id := range jobs {
results <- process(id)
}
for range results {
count++
}
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
- What does Bounded Concurrency Worker Pool print when run?
- Invoke the file as-is — the `processed:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.