How to Implement Bounded Parallelism in Go

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
}