Skip to content

Instantly share code, notes, and snippets.

@jboursiquot
Last active March 15, 2025 09:52
Show Gist options
  • Save jboursiquot/ef53edb815fe18c8160dbe8504dd9d60 to your computer and use it in GitHub Desktop.
Save jboursiquot/ef53edb815fe18c8160dbe8504dd9d60 to your computer and use it in GitHub Desktop.
Limiting the number of running goroutines using semaphores in #golang
var (
concurrency = 5
semaChan = make(chan struct{}, concurrency)
)
func doWork(item int) {
semaChan <- struct{}{} // block while full
go func() {
defer func() {
<-semaChan // read releases a slot
}()
// work
log.Println(item)
time.Sleep(1 * time.Second)
}()
}
func main(){
for i := 0; i <= 1000; i++ {
doWork(i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment