Created
September 30, 2019 19:10
-
-
Save theverything/315bfe94e6d9b59226efa175f014515c to your computer and use it in GitHub Desktop.
Throttle
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 throttle | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
type concurrencyLock struct { | |
locker chan struct{} | |
} | |
func (l *concurrencyLock) Lock() { | |
l.locker <- struct{}{} | |
} | |
func (l *concurrencyLock) Unlock() { | |
<-l.locker | |
} | |
func NewConcurrencyLock(concurrency int) sync.Locker { | |
return &concurrencyLock{ | |
locker: make(chan struct{}, concurrency), | |
} | |
} | |
type Throttler interface { | |
Wait() | |
Go(func()) | |
} | |
type throttle struct { | |
lock sync.Locker | |
wg sync.WaitGroup | |
} | |
func (t *throttle) Go(f func()) { | |
t.wg.Add(1) | |
go func() { | |
defer t.wg.Done() | |
t.lock.Lock() | |
f() | |
t.lock.Unlock() | |
}() | |
} | |
func (t *throttle) Wait() { | |
t.wg.Wait() | |
} | |
func NewThrottler(c int) Throttler { | |
return &throttle{ | |
lock: NewConcurrencyLock(c), | |
wg: sync.WaitGroup{}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment