You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/syncx/managedresource.go

49 lines
1.0 KiB
Go

4 years ago
package syncx
import "sync"
// A ManagedResource is used to manage a resource that might be broken and refetched, like a connection.
4 years ago
type ManagedResource struct {
resource any
4 years ago
lock sync.RWMutex
generate func() any
equals func(a, b any) bool
4 years ago
}
// NewManagedResource returns a ManagedResource.
func NewManagedResource(generate func() any, equals func(a, b any) bool) *ManagedResource {
4 years ago
return &ManagedResource{
generate: generate,
equals: equals,
}
}
// MarkBroken marks the resource broken.
func (mr *ManagedResource) MarkBroken(resource any) {
4 years ago
mr.lock.Lock()
defer mr.lock.Unlock()
if mr.equals(mr.resource, resource) {
mr.resource = nil
}
}
// Take takes the resource, if not loaded, generates it.
func (mr *ManagedResource) Take() any {
4 years ago
mr.lock.RLock()
resource := mr.resource
mr.lock.RUnlock()
if resource != nil {
return resource
}
mr.lock.Lock()
defer mr.lock.Unlock()
// maybe another Take() call already generated the resource.
if mr.resource == nil {
mr.resource = mr.generate()
}
return mr.resource
}