Skip to content

Commit dda17b4

Browse files
committed
use new deepcopy func and avoid concurrent mutation
1 parent 58a7a77 commit dda17b4

1 file changed

Lines changed: 15 additions & 16 deletions

File tree

tsunami/demo/cpuchart/app.go

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -162,32 +162,31 @@ var App = app.DefineComponent("App",
162162
// Collect new CPU data point and shift the data window
163163
cpuDataAtom.SetFn(func(currentData []CPUDataPoint) []CPUDataPoint {
164164
newPoint := generateCPUDataPoint()
165-
// Read current config inside the loop to get live updates
166165
currentDataPointCount := dataPointCountAtom.Get()
167166

167+
// Make a safe copy to avoid mutation issues
168+
data := app.DeepCopy(currentData)
169+
168170
// Ensure we have the right size array
169-
if len(currentData) != currentDataPointCount {
171+
if len(data) != currentDataPointCount {
170172
// Resize array if config changed
171-
newData := make([]CPUDataPoint, currentDataPointCount)
173+
resized := make([]CPUDataPoint, currentDataPointCount)
172174
copyCount := currentDataPointCount
173-
if len(currentData) < copyCount {
174-
copyCount = len(currentData)
175+
if len(data) < copyCount {
176+
copyCount = len(data)
175177
}
176178
if copyCount > 0 {
177-
copy(newData[currentDataPointCount-copyCount:], currentData[len(currentData)-copyCount:])
179+
copy(resized[currentDataPointCount-copyCount:], data[len(data)-copyCount:])
178180
}
179-
currentData = newData
180-
}
181-
// Create a new slice with exact point count
182-
newData := make([]CPUDataPoint, currentDataPointCount)
183-
// Shift existing data left by 1 and add new point at the end
184-
if currentDataPointCount > 1 {
185-
copy(newData, currentData[1:])
181+
data = resized
186182
}
187-
if currentDataPointCount > 0 {
188-
newData[currentDataPointCount-1] = newPoint
183+
184+
// Append new point and keep only the last currentDataPointCount elements
185+
data = append(data, newPoint)
186+
if len(data) > currentDataPointCount {
187+
data = data[len(data)-currentDataPointCount:]
189188
}
190-
return newData
189+
return data
191190
})
192191
// Trigger a re-render
193192
setTickerFn(func(t int) int { return t + 1 })

0 commit comments

Comments
 (0)