Last active
March 15, 2025 09:52
-
-
Save jboursiquot/ef53edb815fe18c8160dbe8504dd9d60 to your computer and use it in GitHub Desktop.
Limiting the number of running goroutines using semaphores in #golang
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
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