Bound work for CPU and I/O workloads
Bound work for CPU and I/O workloads
One goroutine per item is simple for a tiny batch, but huge batches can consume memory, scheduling time and downstream capacity. CPU-bound work spends most of its time computing; I/O-bound work spends much of its time waiting for devices or services. Start with a small explicit worker limit and measure under realistic load. More workers can hide I/O waits but also overload a dependency. CPU-bound workloads may benefit from a limit near available execution capacity; there is no universal optimal count.
package main
import ( "fmt" "sync")
func squares(input []int, workers int) []int { if workers < 1 { panic("workers must be positive") } if workers > len(input) { workers = len(input) } out := make([]int, len(input)) var wg sync.WaitGroup wg.Add(workers) for w := 0; w < workers; w++ { go func(w int) { defer wg.Done() for i := w; i < len(input); i += workers { out[i] = input[i] * input[i] } }(w) } wg.Wait() return out}func main() { fmt.Println(squares([]int{2, 3, 4, 5, 6}, 2)) fmt.Println(squares(nil, 2))}Two workers take disjoint strides (indexes 0,2,4 and 1,3). At most two worker goroutines are launched. We cap workers at input length, so an empty batch creates none; no worker steps by zero. Equal item counts do not ensure equal execution times. Dynamic queues, cancellation and backpressure follow later. This example bounds workers, not input or output memory; constrain those separately.
Expected output:
[4 9 16 25 36][]Model a waiting workload without network calls
package main
import ( "fmt" "sync" "time")
func main() { var wg sync.WaitGroup results := make([]string, 4) wg.Add(2) for w := 0; w < 2; w++ { go func(w int) { defer wg.Done() for i := w; i < len(results); i += 2 { time.Sleep(time.Millisecond) results[i] = "ready" } }(w) } wg.Wait() fmt.Println(results)}The brief sleep models waiting, not actual I/O or a measured speedup. Outputs are stored by index and printed after completion. In a real system choose concurrency based on CPU utilization, queue latency, memory, connection limits and service quotas. Never use Sleep as a completion signal.
Expected output:
[ready ready ready ready]Try it locally
Use at most two workers and strided indexes to add 10 to every element of [1,2,3,4,5]. Print in input order. Test the empty batch too.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency foundations 05: Bound work for CPU and I/O workloads
Check the lesson objective before moving on.
Why might increasing I/O concurrency reduce performance?
What does the strided example explicitly bound?