Junior — Middle
Can a slice be considered safe for use in a multithreaded environment without additional synchronization measures?
sobes.tech AI
Answer from AI
Slices in Go are not thread-safe by default. If multiple goroutines read and write to the same slice without synchronization, data races and unpredictable behavior can occur.
If the slice is only read after initialization, it is safe for concurrent access. But if there are write operations (adding, modifying elements), synchronization mechanisms like sync.Mutex or sync.RWMutex should be used.
Example of using a mutex to protect a slice:
var mu sync.Mutex
var data []int
func appendData(val int) {
mu.Lock()
defer mu.Unlock()
data = append(data, val)
}
func readData(i int) int {
mu.Lock()
defer mu.Unlock()
return data[i]
}
Thus, without additional synchronization, a slice cannot be considered safe for concurrent use.