diff --git a/map.go b/map.go index f864dcf..98a8574 100644 --- a/map.go +++ b/map.go @@ -37,6 +37,21 @@ import ( // // The zero Map is empty and ready to use. // It must not be copied after first use. +// +// In the terminology of [the Go memory model], Map arranges that a write +// operation “synchronizes before” any read operation that observes the effect +// of the write, as sync.Map does. +// [Map.Load], [Map.LoadAndDelete], [Map.LoadOrStore], [Map.Swap], +// [Map.CompareAndSwap], and [Map.CompareAndDelete] are read operations; +// [Map.Store] and [Map.Swap] are write operations; +// [Map.Delete] is a write operation when it deletes an entry; +// [Map.LoadAndDelete] is a write operation when it returns loaded set to true; +// [Map.LoadOrStore] is a write operation when it returns loaded set to false; +// [Map.CompareAndSwap] is a write operation when it returns swapped set to true; +// and [Map.CompareAndDelete] is a write operation when it returns deleted set to true. +// Deleting a missing key writes nothing and takes no lock. +// +// [the Go memory model]: https://go.dev/ref/mem type Map[K comparable, V any] struct { inited atomic.Uint32 initMu sync.Mutex diff --git a/map_internal_test.go b/map_internal_test.go index c56e74e..c09d3c4 100644 --- a/map_internal_test.go +++ b/map_internal_test.go @@ -1,6 +1,9 @@ package gosync -import "testing" +import ( + "testing" + "time" +) func TestInitSlowAlreadyInitialized(t *testing.T) { t.Parallel() @@ -120,3 +123,37 @@ func TestEntryLoadAndDeleteMissing(t *testing.T) { t.Fatalf("loadAndDelete(missing) = %v, %p, %v; want 0, head, false", v, chain, loaded) } } + +// TestDeleteMissingKeyTakesNoLock holds the root lock and deletes keys that +// are not in the map. Like sync.Map, a delete that finds nothing must return +// without locking; with the lock it would block until the timeout. +func TestDeleteMissingKeyTakesNoLock(t *testing.T) { + t.Parallel() + + var m Map[int, int] + m.Store(1, 1) + + root := m.root.Load() + root.mu.Lock() + defer root.mu.Unlock() + + done := make(chan struct{}) + go func() { + defer close(done) + for key := 2; key < 100; key++ { + m.Delete(key) + if _, loaded := m.LoadAndDelete(key); loaded { + t.Errorf("LoadAndDelete(%d) loaded a missing key", key) + } + if m.CompareAndDelete(key, 0, func(a, b int) bool { return a == b }) { + t.Errorf("CompareAndDelete(%d) deleted a missing key", key) + } + } + }() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("deleting a missing key blocked on the node lock") + } +}