Skip to content

Instantly share code, notes, and snippets.

@theverything
Created September 30, 2019 19:10
Show Gist options
  • Save theverything/315bfe94e6d9b59226efa175f014515c to your computer and use it in GitHub Desktop.
Save theverything/315bfe94e6d9b59226efa175f014515c to your computer and use it in GitHub Desktop.
Throttle
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