Skip to content

Commit 9e09bfb

Browse files
committed
Use RWMutex in NSMap and reduce lock area
Signed-off-by: Jin Dong <[email protected]>
1 parent 78b4af7 commit 9e09bfb

1 file changed

Lines changed: 13 additions & 11 deletions

File tree

runtime/nsmap.go

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ type object interface {
3131

3232
// NSMap extends Map type with a notion of namespaces passed via Context.
3333
type NSMap[T object] struct {
34-
mu sync.Mutex
34+
mu sync.RWMutex
3535
objects map[string]map[string]T
3636
}
3737

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

4545
// Get a task
4646
func (m *NSMap[T]) Get(ctx context.Context, id string) (T, error) {
47-
m.mu.Lock()
48-
defer m.mu.Unlock()
4947
namespace, err := namespaces.NamespaceRequired(ctx)
5048
var t T
5149
if err != nil {
5250
return t, err
5351
}
52+
53+
m.mu.RLock()
54+
defer m.mu.RUnlock()
5455
tasks, ok := m.objects[namespace]
5556
if !ok {
5657
return t, errdefs.ErrNotFound
@@ -64,8 +65,8 @@ func (m *NSMap[T]) Get(ctx context.Context, id string) (T, error) {
6465

6566
// GetAll objects under a namespace
6667
func (m *NSMap[T]) GetAll(ctx context.Context, noNS bool) ([]T, error) {
67-
m.mu.Lock()
68-
defer m.mu.Unlock()
68+
m.mu.RLock()
69+
defer m.mu.RUnlock()
6970
var o []T
7071
if noNS {
7172
for ns := range m.objects {
@@ -100,10 +101,10 @@ func (m *NSMap[T]) Add(ctx context.Context, t T) error {
100101

101102
// AddWithNamespace adds a task with the provided namespace
102103
func (m *NSMap[T]) AddWithNamespace(namespace string, t T) error {
104+
id := t.ID()
105+
103106
m.mu.Lock()
104107
defer m.mu.Unlock()
105-
106-
id := t.ID()
107108
if _, ok := m.objects[namespace]; !ok {
108109
m.objects[namespace] = make(map[string]T)
109110
}
@@ -116,21 +117,22 @@ func (m *NSMap[T]) AddWithNamespace(namespace string, t T) error {
116117

117118
// Delete a task
118119
func (m *NSMap[T]) Delete(ctx context.Context, id string) {
119-
m.mu.Lock()
120-
defer m.mu.Unlock()
121120
namespace, err := namespaces.NamespaceRequired(ctx)
122121
if err != nil {
123122
return
124123
}
124+
125+
m.mu.Lock()
126+
defer m.mu.Unlock()
125127
tasks, ok := m.objects[namespace]
126128
if ok {
127129
delete(tasks, id)
128130
}
129131
}
130132

131133
func (m *NSMap[T]) IsEmpty() bool {
132-
m.mu.Lock()
133-
defer m.mu.Unlock()
134+
m.mu.RLock()
135+
defer m.mu.RUnlock()
134136

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

0 commit comments

Comments
 (0)