Bounded Concurrency Worker Pool

Cap in-flight work with a semaphore channel so a large batch never opens more connections than the upstream tolerates.

GoResilience

Code

snippet
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

FAQ

What does Bounded Concurrency Worker Pool print when run?
Invoke the file as-is — the `processed:` prefixes identify which step printed each line.