Senior
Is concurrent access to a slice safe? Will there be a race condition if 4 goroutines modify their own unique index of the slice?
sobes.tech AI
Answer from AI
In Go, concurrent access to a slice is not safe by itself, because a slice is a structure containing a pointer to an array, a length, and a capacity. However, if 4 goroutines modify each their unique index of the slice and do not change the length or capacity of the slice, then there will be no data race, because each goroutine works with a separate element.
It is important that:
- The slice is pre-allocated with the required size.
- The structure of the slice is not changed (for example, by append) during writing.
Example:
s := make([]int, 4)
var wg sync.WaitGroup
wg.Add(4)
for i := 0; i < 4; i++ {
go func(i int) {
defer wg.Done()
s[i] = i * 10
}(i)
}
wg.Wait()
In this example, there will be no race conditions, as each goroutine writes to a unique index.
If multiple goroutines can change the length of the slice or work with the same index, synchronization is needed.