go-zero/core/syncx/refresource.go

54 lines
892 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"errors"
"sync"
)
2021-02-28 16:16:22 +08:00
// ErrUseOfCleaned is an error that indicates using a cleaned resource.
2020-07-26 17:09:05 +08:00
var ErrUseOfCleaned = errors.New("using a cleaned resource")
2021-05-10 00:09:00 +08:00
// A RefResource is used to reference counting a resource.
2020-07-26 17:09:05 +08:00
type RefResource struct {
lock sync.Mutex
ref int32
cleaned bool
clean func()
}
2021-02-28 16:16:22 +08:00
// NewRefResource returns a RefResource.
2020-07-26 17:09:05 +08:00
func NewRefResource(clean func()) *RefResource {
return &RefResource{
clean: clean,
}
}
2021-02-28 16:16:22 +08:00
// Use uses the resource with reference count incremented.
2020-07-26 17:09:05 +08:00
func (r *RefResource) Use() error {
r.lock.Lock()
defer r.lock.Unlock()
if r.cleaned {
return ErrUseOfCleaned
}
r.ref++
return nil
}
2021-02-28 16:16:22 +08:00
// Clean cleans a resource with reference count decremented.
2020-07-26 17:09:05 +08:00
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()
}
}