Skip to content
Myr

fix(context): load Keys under the mutex in Copy (#4854)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Copy read c.Keys before RLock. Set stores that field under Lock when the map is created. The race detector reports the unsynchronized access, and the copy can observe a nil header and drop keys Set has already published. maps.Clone(nil) returns nil, so the load and the clone belong in the same critical section. Map iteration was already under the mutex.

authored by HazyLab · committed by GitHub · parent 3b08cd7 · Browse files · 2 files+25 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: hazyhaar <hazyhaarlabs@gmail.com>

Diff stats

2 files+25 added−2 removed

  • other:+25 added−2 removed

2 files+25 added−2 removed

modified:context_test.go+24 added
707 unmodified lines
708 assert.Equal(t, m, c.GetStringMapStringSlice("map"))709 assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"])710}711712func TestCopyConcurrentWithSet(t *testing.T) {713 c := &Context{}714 var wg sync.WaitGroup715 wg.Add(2)716 go func() {717 defer wg.Done()718 for i := 0; i < 100; i++ {719 c.Set(i, i)720 }721 }()722 go func() {723 defer wg.Done()724 for i := 0; i < 100; i++ {725 cp := c.Copy()726 for k, v := range cp.Keys {727 if k != v {728 t.Errorf("copied key %v = %v, want %v", k, v, k)729 }730 }731 }732 }()733 wg.Wait()734}735736func TestContextCopy(t *testing.T) {737 c, _ := CreateTestContext(httptest.NewRecorder())738 c.index = 2739 c.Request, _ = http.NewRequest(http.MethodPost, "/hola", nil)
3318 unmodified lines
modified:context.go+1 added-2 removed
130 unmodified lines
131 cp.index = abortIndex132 cp.handlers = nil133 cp.fullPath = c.fullPath134135 cKeys := c.Keys135 c.mu.RLock()137 cp.Keys = maps.Clone(cKeys)136 cp.Keys = maps.Clone(c.Keys)137 c.mu.RUnlock()138139 cParams := c.Params140 cp.Params = make([]Param, len(cParams))
1403 unmodified lines