Created
December 5, 2017 07:13
-
-
Save yogeshnarayanan/325b472853f71aa0e703fdba45788d00 to your computer and use it in GitHub Desktop.
Limiting number of goroutines (concurrency) in golang
This file contains 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
concurrency := 10 // 10 is max concurrency | |
sem := make(chan bool, concurrency) | |
urls := []string{"url1", "url2"} | |
for _, url := range urls { | |
sem <- true // mark one as running (will block when full) | |
go func(url) { | |
defer func() { <-sem }() // mark one as completed | |
// Do something with the url | |
}(url) | |
} | |
//to make sure we wait for all of them to finish | |
for i := 0; i < cap(sem); i++ { | |
sem <- true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment