From fa5e94f2c445d1bdaa4e495dc6c134961ba61076 Mon Sep 17 00:00:00 2001 From: gucio321 Date: Wed, 27 Nov 2024 19:37:21 +0100 Subject: [PATCH 1/2] context: use sync.Map for widget counter while work on HellSpawner, turns out that there is a data race on this file --- Context.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Context.go b/Context.go index 4d64433f..2c6e70a0 100644 --- a/Context.go +++ b/Context.go @@ -13,13 +13,15 @@ import ( // GenAutoID automatically generates widget's ID. // It returns an unique value each time it is called. func GenAutoID(id string) ID { - idx, ok := Context.widgetIndex[id] + idx := int(0) + idxAny, ok := Context.widgetIndex.Load(id) if ok { + idx = idxAny.(int) idx++ } - Context.widgetIndex[id] = idx + Context.widgetIndex.Store(id, idx) return ID(fmt.Sprintf("%s##%d", id, idx)) } @@ -51,7 +53,7 @@ type GIUContext struct { isRunning bool - widgetIndex map[string]int + widgetIndex sync.Map // Indicate whether current application is running isAlive bool @@ -83,7 +85,6 @@ func CreateContext(b backend.Backend[glfwbackend.GLFWWindowFlags]) *GIUContext { textureLoadingQueue: queue.New(), textureFreeingQueue: queue.New(), m: &sync.Mutex{}, - widgetIndex: make(map[string]int), } // Create font @@ -140,7 +141,7 @@ func (c *GIUContext) cleanStates() { return true }) - c.widgetIndex = make(map[string]int) + c.widgetIndex.Clear() c.dirty = false } From cad1b8dee6cfec32792d962c8db4e65a5e26f1b8 Mon Sep 17 00:00:00 2001 From: gucio321 Date: Wed, 27 Nov 2024 19:40:59 +0100 Subject: [PATCH 2/2] check type assertion --- Context.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Context.go b/Context.go index 2c6e70a0..94930fa2 100644 --- a/Context.go +++ b/Context.go @@ -17,7 +17,9 @@ func GenAutoID(id string) ID { idxAny, ok := Context.widgetIndex.Load(id) if ok { - idx = idxAny.(int) + idx, ok = idxAny.(int) + Assert(ok, "Context", "GenAutoID", "unexpected type of widgetIndex value: expected int, instead found %T", idxAny) + idx++ }