Skip to content

Instantly share code, notes, and snippets.

@guiajlopes
Last active October 28, 2018 13:31
Show Gist options
  • Select an option

  • Save guiajlopes/37fb7ead0e85da1be42f304a0696d9d9 to your computer and use it in GitHub Desktop.

Select an option

Save guiajlopes/37fb7ead0e85da1be42f304a0696d9d9 to your computer and use it in GitHub Desktop.
Go buffered channel
import (
"sync"
"fmt"
)
func maxGoRoutinesExample(maxNumberOfConnections int) {
var wg sync.WaitGroup
guard := make(chan int, maxNumberOfConnections)
for i := 0; i < 100; i++ {
wg.Add(1)
// Add to a channel.
guard <- 1
go func() {
// This make sure that you finish the wait group.
defer wg.Done()
doAnything()
// Remove form channel when finish
<-guard
}()
}
// Wait all go routines to finish
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment