Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. package throttle
  2.  
  3. import (
  4. "fmt"
  5. "sync"
  6. "time"
  7. )
  8.  
  9. type concurrencyLock struct {
  10. locker chan struct{}
  11. }
  12.  
  13. func (l *concurrencyLock) Lock() {
  14. l.locker <- struct{}{}
  15. }
  16.  
  17. func (l *concurrencyLock) Unlock() {
  18. <-l.locker
  19. }
  20.  
  21. func NewConcurrencyLock(concurrency int) sync.Locker {
  22. return &concurrencyLock{
  23. locker: make(chan struct{}, concurrency),
  24. }
  25. }
  26.  
  27. type Throttler interface {
  28. Wait()
  29. Go(func())
  30. }
  31.  
  32. type throttle struct {
  33. lock sync.Locker
  34. wg sync.WaitGroup
  35. }
  36.  
  37. func (t *throttle) Go(f func()) {
  38. t.wg.Add(1)
  39. go func() {
  40. defer t.wg.Done()
  41.  
  42. t.lock.Lock()
  43. f()
  44. t.lock.Unlock()
  45.  
  46. }()
  47. }
  48.  
  49. func (t *throttle) Wait() {
  50. t.wg.Wait()
  51. }
  52.  
  53. func NewThrottler(c int) Throttler {
  54. return &throttle{
  55. lock: NewConcurrencyLock(c),
  56. wg: sync.WaitGroup{},
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement