Ghytro

rate_limiter.go

Sep 25th, 2024
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.73 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math/rand"
  6.     "sync"
  7.     "time"
  8. )
  9.  
  10. func main() {
  11.     count := 50
  12.     ch := make(chan int, count)
  13.     RPCCall := MakeRPCCall()
  14.     wg := sync.WaitGroup{}
  15.     for i := 0; i < count; i++ {
  16.         wg.Add(1)
  17.         go func() {
  18.             defer wg.Done()
  19.             ch <- RPCCall()
  20.         }()
  21.     }
  22.  
  23.     wg.Wait()
  24.     close(ch)
  25.     for value := range ch {
  26.         fmt.Println(value)
  27.     }
  28. }
  29.  
  30. const rateLimit = 10
  31.  
  32. func MakeRPCCall() func() int {
  33.     jobs := make(chan struct{}, rateLimit)
  34.     go func() {
  35.         for {
  36.             time.Sleep(time.Second)
  37.             chanLen := len(jobs)
  38.             if chanLen > rateLimit {
  39.                 chanLen = rateLimit
  40.             }
  41.             for i := 0; i < chanLen; i++ {
  42.                 <-jobs
  43.             }
  44.         }
  45.     }()
  46.     return func() int {
  47.         jobs <- struct{}{}
  48.         return rand.Int()
  49.     }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment