Last active
August 29, 2015 14:07
-
-
Save Mistobaan/f120adf14e3f32f32d47 to your computer and use it in GitHub Desktop.
RequestLimiter
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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"runtime" | |
"sync" | |
"time" | |
) | |
// RequestLimiter to the number of request in that period of time | |
func RequestLimiter(timePeriod time.Duration, maxReq int) <-chan struct{} { | |
ch := make(chan struct{}, maxReq) | |
t := time.NewTimer(timePeriod) | |
go func() { | |
for { | |
expired := false | |
t.Reset(timePeriod) | |
for i := 0; i < maxReq; i++ { | |
select { | |
case <-t.C: | |
expired = true | |
break | |
case ch <- struct{}{}: | |
} | |
} | |
if !expired { | |
<-t.C | |
} | |
runtime.Gosched() | |
} | |
}() | |
return ch | |
} | |
func main() { | |
var wg sync.WaitGroup | |
gauge := RequestLimiter(time.Second, 100) | |
for i := 0; i < 10; i++ { | |
wg.Add(1) | |
id := i | |
go func() { | |
defer wg.Done() | |
for t := range gauge { | |
fmt.Println(id, t) | |
<-time.After(time.Duration(rand.Intn(100)) * time.Millisecond) | |
} | |
}() | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment