Implement bounded parallelism in Go by using a buffered channel as a semaphore to control the number of active goroutines.
Use a buffered channel as a semaphore to limit the number of concurrent goroutines.
sem := make(chan struct{}, 5) // Max 5 concurrent workers
for _, item := range items {
sem <- struct{}{} // Acquire slot
go func(i interface{}) {
defer func() { <-sem }() // Release slot
process(i)
}(item)
}
// Wait for all goroutines to finish
for range items {
<-sem
}
Bounded parallelism in Go acts like a ticket system for your code. You create a pool of tickets (the buffer size) and a worker must grab a ticket before starting work. When they finish, they return the ticket. This ensures only a specific number of tasks run at once, preventing your system from being overwhelmed.