chore: optimize lock in discov.etcd (#4275)

This commit is contained in:
Kevin Wan 2024-07-27 16:27:05 +08:00 committed by GitHub
parent 0e61303cb0
commit caf0e64beb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -30,7 +30,7 @@ var (
// A Registry is a registry that manages the etcd client connections.
type Registry struct {
clusters map[string]*cluster
lock sync.Mutex
lock sync.RWMutex
}
// GetRegistry returns a global Registry.
@ -60,13 +60,20 @@ func (r *Registry) Monitor(endpoints []string, key string, l UpdateListener) err
func (r *Registry) getCluster(endpoints []string) (c *cluster, exists bool) {
clusterKey := getClusterKey(endpoints)
r.lock.RLock()
c, exists = r.clusters[clusterKey]
r.lock.RUnlock()
if !exists {
r.lock.Lock()
defer r.lock.Unlock()
// double-check locking
c, exists = r.clusters[clusterKey]
if !exists {
c = newCluster(endpoints)
r.clusters[clusterKey] = c
}
}
return
}