This commit is contained in:
Joe Tsai 2024-04-25 12:05:25 +02:00 committed by GitHub
commit c9d7783f34
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 13 deletions

View File

@ -245,8 +245,10 @@ func (m *Map[K, V]) Delete(key K) {
delete(m.m, key)
}
// Range iterates over the map in undefined order calling f for each entry.
// Range iterates over the map in an undefined order calling f for each entry.
// Iteration stops if f returns false. Map changes are blocked during iteration.
// A read lock is held for the entire duration of the iteration.
// Use the [WithLock] method instead to mutate the map during iteration.
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
m.mu.RLock()
defer m.mu.RUnlock()
@ -257,6 +259,15 @@ func (m *Map[K, V]) Range(f func(key K, value V) bool) {
}
}
// WithLock calls f with the underlying map.
// Use of m2 must not escape the duration of this call.
// The write-lock is held for the entire duration of this call.
func (m *Map[K, V]) WithLock(f func(m2 map[K]V)) {
m.mu.Lock()
defer m.mu.Unlock()
f(m.m)
}
// Len returns the length of the map.
func (m *Map[K, V]) Len() int {
m.mu.RLock()

View File

@ -5,7 +5,6 @@ package syncs
import (
"context"
"sync"
"testing"
"github.com/google/go-cmp/cmp"
@ -134,19 +133,11 @@ func TestMap(t *testing.T) {
t.Run("LoadOrStore", func(t *testing.T) {
var m Map[string, string]
var wg sync.WaitGroup
wg.Add(2)
var wg WaitGroup
var ok1, ok2 bool
go func() {
defer wg.Done()
_, ok1 = m.LoadOrStore("", "")
}()
go func() {
defer wg.Done()
_, ok2 = m.LoadOrStore("", "")
}()
wg.Go(func() { _, ok1 = m.LoadOrStore("", "") })
wg.Go(func() { _, ok2 = m.LoadOrStore("", "") })
wg.Wait()
if ok1 == ok2 {
t.Errorf("exactly one LoadOrStore should load")
}