Sobes.tech
Junior — Middle

Разрешено ли одновременно модифицировать слайс из нескольких потоков?

sobes.tech AI

Answer from AI

In Go, concurrent modification of a slice from multiple goroutines without synchronization is not allowed and can lead to data races and unpredictable behavior. A slice in Go is a structure containing a pointer to an array, a length, and a capacity, and when writing to elements or changing length/capacity, access must be safe.

To safely work with a slice in multiple goroutines, use synchronization mechanisms such as sync.Mutex or channels.

Example with mutex:

var mu sync.Mutex
var s []int

func appendSafe(val int) {
    mu.Lock()
    s = append(s, val)
    mu.Unlock()
}

Without such synchronization, data races and slice corruption are possible.