From 2aa2cc6a72fbc9de6f96332d013d1073061dd6e9 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Mon, 29 Jan 2024 16:19:47 -0800 Subject: [PATCH] container: fix data race Before: go test -race -run=TestContainer_Remove_Race . ================== WARNING: DATA RACE Read at 0x00c0000b63a0 by goroutine 12: fyne.io/fyne/v2.(*Container).Remove() /Users/josh/x/fyne/container.go:132 +0x44 fyne.io/fyne/v2.TestContainer_Remove_Race.func1() /Users/josh/x/fyne/container_test.go:123 +0x4c Previous write at 0x00c0000b63a0 by goroutine 9: fyne.io/fyne/v2.(*Container).Remove() /Users/josh/x/fyne/container.go:147 +0x258 fyne.io/fyne/v2.TestContainer_Remove_Race.func1() /Users/josh/x/fyne/container_test.go:123 +0x4c Goroutine 12 (running) created at: fyne.io/fyne/v2.TestContainer_Remove_Race() /Users/josh/x/fyne/container_test.go:122 +0x184 testing.tRunner() /Users/josh/go/1.21/src/testing/testing.go:1595 +0x1b0 testing.(*T).Run.func1() /Users/josh/go/1.21/src/testing/testing.go:1648 +0x40 Goroutine 9 (finished) created at: fyne.io/fyne/v2.TestContainer_Remove_Race() /Users/josh/x/fyne/container_test.go:122 +0x184 testing.tRunner() /Users/josh/go/1.21/src/testing/testing.go:1595 +0x1b0 testing.(*T).Run.func1() /Users/josh/go/1.21/src/testing/testing.go:1648 +0x40 ================== --- FAIL: TestContainer_Remove_Race (0.00s) testing.go:1465: race detected during execution of test FAIL FAIL fyne.io/fyne/v2 0.160s FAIL --- container.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/container.go b/container.go index 4c8992921c..726e77a626 100644 --- a/container.go +++ b/container.go @@ -129,12 +129,12 @@ func (c *Container) Refresh() { // This method is not intended to be used inside a loop, to remove all the elements. // It is much more efficient to call RemoveAll() instead. func (c *Container) Remove(rem CanvasObject) { + c.lock.Lock() + defer c.lock.Unlock() if len(c.Objects) == 0 { return } - c.lock.Lock() - defer c.lock.Unlock() for i, o := range c.Objects { if o != rem { continue