Sobes.tech
Senior

What will happen in the end to the length of the array when appending concurrently from 1000 goroutines?

sobes.tech AI

Answer from AI

When append is called concurrently on the same slice from 1000 goroutines without synchronization (for example, without a mutex), the behavior will be undefined. As a result, the length of the array may be less than expected, since write operations will conflict, overwrite each other, or cause a panic.

Append is not an atomic operation and involves reading the length, writing an element, and updating the length. Concurrent access without locks can lead to data races.

To correctly add elements from multiple goroutines, synchronization should be used, such as sync.Mutex or channels.

Example with mutex:

var mu sync.Mutex
var slice []int

wg := sync.WaitGroup{}
for i := 0; i < 1000; i++ {
    wg.Add(1)
    go func(val int) {
        defer wg.Done()
        mu.Lock()
        slice = append(slice, val)
        mu.Unlock()
    }(i)
}
wg.Wait()
fmt.Println(len(slice)) // will be 1000

Without a mutex, the length may be less than 1000 or the program may crash.