Skip to content

Instantly share code, notes, and snippets.

@yogeshnarayanan
Created December 5, 2017 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yogeshnarayanan/325b472853f71aa0e703fdba45788d00 to your computer and use it in GitHub Desktop.
Save yogeshnarayanan/325b472853f71aa0e703fdba45788d00 to your computer and use it in GitHub Desktop.
Limiting number of goroutines (concurrency) in golang
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