Sobes.tech
Middle+

What will be output when running the program: func main() { counter := make([]int, 0, 1000) var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func() { defer wg.Done() counter = append(counter, i) time.Sleep(10 * time.Millisecond) // Simulate work }() } wg.Wait() fmt.Println(len(counter)) }

sobes.tech AI

Answer from AI

The program contains a data race when writing to the slice counter from multiple goroutines without synchronization. This leads to unpredictable behavior.

What happens:

  • A slice counter is created with length 0 and capacity 1000.
  • 1000 goroutines are launched, each trying to add the value i to the slice.
  • The append operation is not thread-safe, and multiple goroutines modify the slice simultaneously.
  • Due to the data race, data loss, slice corruption, or a panic may occur.

In the output:

  • The value of len(counter) may be less than 1000, as some entries might be lost.
  • A panic or incorrect output is possible.

The correct approach is to use a mutex or a channel to synchronize access to the slice:

var mu sync.Mutex

for i := 0; i < 1000; i++ {
    wg.Add(1)
    go func(val int) {
        defer wg.Done()
        mu.Lock()
        counter = append(counter, val)
        mu.Unlock()
        time.Sleep(10 * time.Millisecond)
    }(i)
}

Or use thread-safe data structures.

What will be output when running the program: func… - sobes.tech