Skip to content

Commit 953dc28

Browse files
committed
Use RWMutex for ConcurrentStringStringMap and improve test performance.
1 parent a5ce4aa commit 953dc28

File tree

2 files changed

+17
-14
lines changed

2 files changed

+17
-14
lines changed

concurrentmap.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,40 +26,40 @@ import (
2626
)
2727

2828
type ConcurrentStringStringMap struct {
29-
sync.Mutex
30-
d map[string]string
29+
mu sync.RWMutex
30+
d map[string]string
3131
}
3232

3333
func (m *ConcurrentStringStringMap) Set(key, value string) {
34-
m.Lock()
35-
defer m.Unlock()
34+
m.mu.Lock()
35+
defer m.mu.Unlock()
3636
if m.d == nil {
3737
m.d = make(map[string]string)
3838
}
3939
m.d[key] = value
4040
}
4141

4242
func (m *ConcurrentStringStringMap) Get(key string) (string, bool) {
43-
m.Lock()
44-
defer m.Unlock()
43+
m.mu.RLock()
44+
defer m.mu.RUnlock()
4545
s, found := m.d[key]
4646
return s, found
4747
}
4848

4949
func (m *ConcurrentStringStringMap) Del(key string) {
50-
m.Lock()
51-
defer m.Unlock()
50+
m.mu.Lock()
51+
defer m.mu.Unlock()
5252
delete(m.d, key)
5353
}
5454

5555
func (m *ConcurrentStringStringMap) Len() int {
56-
m.Lock()
57-
defer m.Unlock()
56+
m.mu.RLock()
57+
defer m.mu.RUnlock()
5858
return len(m.d)
5959
}
6060

6161
func (m *ConcurrentStringStringMap) Clear() {
62-
m.Lock()
63-
defer m.Unlock()
62+
m.mu.Lock()
63+
defer m.mu.Unlock()
6464
m.d = nil
6565
}

concurrentmap_test.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,11 @@ func TestConcurrentStringStringMap(t *testing.T) {
8686
for y := 0; y < count; y = y + 1 {
8787
value := rnd + "-" + strconv.Itoa(y)
8888
m.Set(key, value)
89-
if v, found := m.Get(key); !assert.True(found, "Expected entry for key %s", key) ||
90-
!assert.Equal(value, v, "Unexpected value for key %s", key) {
89+
if v, found := m.Get(key); !found {
90+
assert.True(found, "Expected entry for key %s", key)
91+
return
92+
} else if v != value {
93+
assert.Equal(value, v, "Unexpected value for key %s", key)
9194
return
9295
}
9396
}

0 commit comments

Comments
 (0)