Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use RWMutex in NSMap and reduce lock area #8684

Merged
merged 1 commit into from
Jun 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions runtime/nsmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type object interface {

// NSMap extends Map type with a notion of namespaces passed via Context.
type NSMap[T object] struct {
mu sync.Mutex
mu sync.RWMutex
objects map[string]map[string]T
}

Expand All @@ -44,13 +44,14 @@ func NewNSMap[T object]() *NSMap[T] {

// Get a task
func (m *NSMap[T]) Get(ctx context.Context, id string) (T, error) {
m.mu.Lock()
defer m.mu.Unlock()
namespace, err := namespaces.NamespaceRequired(ctx)
var t T
if err != nil {
return t, err
}

m.mu.RLock()
defer m.mu.RUnlock()
tasks, ok := m.objects[namespace]
if !ok {
return t, errdefs.ErrNotFound
Expand All @@ -64,8 +65,8 @@ func (m *NSMap[T]) Get(ctx context.Context, id string) (T, error) {

// GetAll objects under a namespace
func (m *NSMap[T]) GetAll(ctx context.Context, noNS bool) ([]T, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.mu.RLock()
defer m.mu.RUnlock()
var o []T
if noNS {
for ns := range m.objects {
Expand Down Expand Up @@ -100,10 +101,10 @@ func (m *NSMap[T]) Add(ctx context.Context, t T) error {

// AddWithNamespace adds a task with the provided namespace
func (m *NSMap[T]) AddWithNamespace(namespace string, t T) error {
id := t.ID()

m.mu.Lock()
defer m.mu.Unlock()

id := t.ID()
if _, ok := m.objects[namespace]; !ok {
m.objects[namespace] = make(map[string]T)
}
Expand All @@ -116,21 +117,22 @@ func (m *NSMap[T]) AddWithNamespace(namespace string, t T) error {

// Delete a task
func (m *NSMap[T]) Delete(ctx context.Context, id string) {
m.mu.Lock()
defer m.mu.Unlock()
namespace, err := namespaces.NamespaceRequired(ctx)
if err != nil {
return
}

m.mu.Lock()
defer m.mu.Unlock()
tasks, ok := m.objects[namespace]
if ok {
delete(tasks, id)
}
}

func (m *NSMap[T]) IsEmpty() bool {
m.mu.Lock()
defer m.mu.Unlock()
m.mu.RLock()
defer m.mu.RUnlock()

for ns := range m.objects {
if len(m.objects[ns]) > 0 {
Expand Down