Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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{},
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement