Skip to content

Instantly share code, notes, and snippets.

@mattbajorek
Created August 2, 2022 04:46
Show Gist options
  • Save mattbajorek/6adfb5ff8f5bbfd5ee61f3d31b40505e to your computer and use it in GitHub Desktop.
Save mattbajorek/6adfb5ff8f5bbfd5ee61f3d31b40505e to your computer and use it in GitHub Desktop.
Max concurrent requests limiter
package main
import (
"fmt"
"sync"
"time"
)
func main() {
// Create request limiter
// Only 10 requests are allowed to be in flight at a time
maxConcurrentRequestsLimiterChannel := maxConcurrentRequestsLimiter(10)
var waitGroup sync.WaitGroup
for i := 0; i < 50; i++ {
waitGroup.Add(1)
go func(id int) {
fmt.Printf("Waiting to request %d\n", id)
// 1. No wait if concurrent requests is less than limit
// 2. Waits once a concurrent request finishes
maxConcurrentRequestsLimiterChannel <- true
// Need to signal request was completed
defer func() {
<-maxConcurrentRequestsLimiterChannel
}()
fmt.Printf("Making request %d\n", id)
<-time.After(3 * time.Second)
fmt.Printf("Maked request %d\n", id)
waitGroup.Done()
}(i)
}
waitGroup.Wait()
}
func maxConcurrentRequestsLimiter(concurrentRequests uint) chan bool {
return make(chan bool, concurrentRequests)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment