Last active
October 28, 2018 13:31
-
-
Save guiajlopes/37fb7ead0e85da1be42f304a0696d9d9 to your computer and use it in GitHub Desktop.
Go buffered channel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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