Skip to content
Merged
Show file tree
Hide file tree
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
15 changes: 15 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 38 additions & 1 deletion map_internal_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package gosync

import "testing"
import (
"testing"
"time"
)

func TestInitSlowAlreadyInitialized(t *testing.T) {
t.Parallel()
Expand Down Expand Up @@ -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")
}
}
Loading