forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
refresource.go
53 lines (43 loc) · 891 Bytes
/
refresource.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
package syncx
import (
"errors"
"sync"
)
// ErrUseOfCleaned is an error that indicates using a cleaned resource.
var ErrUseOfCleaned = errors.New("using a cleaned resource")
// A RefResource is used to reference counting a resouce.
type RefResource struct {
lock sync.Mutex
ref int32
cleaned bool
clean func()
}
// NewRefResource returns a RefResource.
func NewRefResource(clean func()) *RefResource {
return &RefResource{
clean: clean,
}
}
// Use uses the resource with reference count incremented.
func (r *RefResource) Use() error {
r.lock.Lock()
defer r.lock.Unlock()
if r.cleaned {
return ErrUseOfCleaned
}
r.ref++
return nil
}
// Clean cleans a resource with reference count decremented.
func (r *RefResource) Clean() {
r.lock.Lock()
defer r.lock.Unlock()
if r.cleaned {
return
}
r.ref--
if r.ref == 0 {
r.cleaned = true
r.clean()
}
}