forked from juju/utils
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlimiter.go
59 lines (51 loc) · 1.41 KB
/
limiter.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
55
56
57
58
59
// Copyright 2011, 2012, 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package utils
import (
"fmt"
)
type empty struct{}
type limiter chan empty
// Limiter represents a limited resource (eg a semaphore).
type Limiter interface {
// Acquire another unit of the resource.
// Acquire returns false to indicate there is no more availability,
// until another entity calls Release.
Acquire() bool
// AcquireWait requests a unit of resource, but blocks until one is
// available.
AcquireWait()
// Release returns a unit of the resource. Calling Release when there
// are no units Acquired is an error.
Release() error
}
func NewLimiter(max int) Limiter {
return make(limiter, max)
}
// Acquire requests some resources that you can return later
// It returns 'true' if there are resources available, but false if they are
// not. Callers are responsible for calling Release if this returns true, but
// should not release if this returns false.
func (l limiter) Acquire() bool {
e := empty{}
select {
case l <- e:
return true
default:
return false
}
}
// AcquireWait waits for the resource to become available before returning.
func (l limiter) AcquireWait() {
e := empty{}
l <- e
}
// Release returns the resource to the available pool.
func (l limiter) Release() error {
select {
case <-l:
return nil
default:
return fmt.Errorf("Release without an associated Acquire")
}
}