Add ConcurrencyLimit

This commit is contained in:
Ian Gulliver
2021-09-26 04:21:03 +00:00
parent eca6f180a3
commit 1846eb45bc
3 changed files with 36 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
package client
import "context"
import "golang.org/x/sync/semaphore"
type ConcurrencyLimit struct {
sem *semaphore.Weighted
}
func NewConcurrencyLimit(limit int64) *ConcurrencyLimit {
return &ConcurrencyLimit{
sem: semaphore.NewWeighted(limit),
}
}
func (cl *ConcurrencyLimit) Acquire1() {
cl.AcquireN(1)
}
func (cl *ConcurrencyLimit) AcquireN(cost int64) {
err := cl.sem.Acquire(context.TODO(), cost)
if err != nil {
panic(err)
}
}
func (cl *ConcurrencyLimit) Release1() {
cl.ReleaseN(1)
}
func (cl *ConcurrencyLimit) ReleaseN(cost int64) {
cl.sem.Release(cost)
}