-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlock.go
54 lines (44 loc) · 862 Bytes
/
lock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"context"
"errors"
"sync"
"github.com/joshbohde/codel"
"golang.org/x/sync/semaphore"
)
type Locker interface {
Acquire(ctx context.Context) error
Release()
}
type Semaphore struct {
mu sync.Mutex
cur int64
cap int64
limit int64
sem *semaphore.Weighted
}
func NewSemaphore(opts codel.Options) *Semaphore {
s := semaphore.NewWeighted(int64(opts.MaxOutstanding))
return &Semaphore{
cap: int64(opts.MaxPending) + int64(opts.MaxOutstanding),
limit: int64(opts.MaxOutstanding),
sem: s,
}
}
func (s *Semaphore) Acquire(ctx context.Context) error {
s.mu.Lock()
// Drop if queue is full
if s.cur >= s.cap {
s.mu.Unlock()
return errors.New("dropped")
}
s.cur++
s.mu.Unlock()
return s.sem.Acquire(ctx, 1)
}
func (s *Semaphore) Release() {
s.mu.Lock()
s.cur--
s.mu.Unlock()
s.sem.Release(1)
}