Skip to content
Open
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
26 changes: 20 additions & 6 deletions src/sync/map.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package sync

import "internal/task"
import (
"internal/task"
)

// This file implements just enough of sync.Map to get packages to compile. It
// is no more efficient than a map with a lock.
Expand Down Expand Up @@ -56,15 +58,27 @@ func (m *Map) Store(key, value interface{}) {
m.m[key] = value
}

// Range calls f for each key and value in the map. If f returns false, the iteration stops.
func (m *Map) Range(f func(key, value interface{}) bool) {
m.lock.Lock()
defer m.lock.Unlock()
// Iterate over a snapshot instead of holding the lock across the callback,
// to prevent deadlock when a Map method is called inside f.
//
// Using a snapshot in Map.Range is sufficient because Go specifies that:
// - Range only requires that no key is visited more than once, and
// - Range may reflect any mapping from any point during the Range call.

if m.m == nil {
return
var snapshot map[interface{}]interface{}

m.lock.Lock()
if m.m != nil {
snapshot = make(map[interface{}]interface{}, len(m.m))
for k, v := range m.m {
snapshot[k] = v
}
}
m.lock.Unlock()

for k, v := range m.m {
for k, v := range snapshot {
if !f(k, v) {
break
}
Expand Down
28 changes: 28 additions & 0 deletions src/sync/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,31 @@ func TestMapSwap(t *testing.T) {
t.Errorf("Load after Swap returned %v, %v, want foo, true", v, ok)
}
}

func TestMapRangeAndDelete(t *testing.T) {
var sm sync.Map
sm.Store(0, "0")
sm.Store(1, "1")
sm.Store(2, "2")

sm.Range(func(k, v any) bool {
keyAsInt, ok := k.(int)
if !ok {
return true
}
if keyAsInt%2 == 0 {
sm.Delete(keyAsInt)
}
return true
})

if v, ok := sm.Load(0); ok {
t.Errorf("Load(0) after Delete returned %v, %v, want nil, false", v, ok)
}
if v, ok := sm.Load(1); !ok || v.(string) != "1" {
t.Errorf("Load(1) after Delete returned %v, %v, want \"1\", true", v, ok)
}
if v, ok := sm.Load(2); ok {
t.Errorf("Load(2) after Delete returned %v, %v, want nil, false", v, ok)
}
}
Loading