Sobes.tech
Senior

What is the problem with concurrent access to a slice without a mutex? How to fix it?

sobes.tech AI

Answer from AI

Concurrent access to a slice in Go without using a mutex can lead to data races. For example, if multiple goroutines read and write to a slice simultaneously, it can cause data corruption, panics, or unpredictable program behavior.

This occurs because operations like adding, removing, or modifying elements in a slice are not atomic and may involve changing the internal structure (such as increasing capacity and allocating new memory).

To fix this issue, access to the slice should be synchronized using a mutex (sync.Mutex) or other synchronization mechanisms, such as sync.RWMutex for separating read and write operations, or channels for passing data between goroutines.

Example with a mutex:

var mu sync.Mutex
var slice []int

func appendValue(val int) {
    mu.Lock()
    defer mu.Unlock()
    slice = append(slice, val)
}

func readSlice() []int {
    mu.Lock()
    defer mu.Unlock()
    copied := make([]int, len(slice))
    copy(copied, slice)
    return copied
}

Thus, the mutex ensures that only one goroutine can modify or read the slice at any given time, preventing data races.