Sobes.tech
Senior

//What will be printed 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

This code has a problem with concurrent access to the counter slice from multiple goroutines without synchronization.

Each goroutine attempts to execute counter = append(counter, i), but:

  • append is not an atomic operation and can modify the underlying array,
  • concurrent access without locks leads to data races,
  • the variable i in the closure is not captured correctly (all goroutines use the same i value after the loop).

What will be output:

  • Most likely, the program will panic due to concurrent modification of the slice without protection,
  • If no panic occurs, the length of counter will be less than 1000 or unpredictable due to races.

The correct approach is to capture i in the function argument and use a mutex to protect the slice:

func main() {
    counter := make([]int, 0, 1000)
    var mu sync.Mutex
    var wg sync.WaitGroup

    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)
    }

    wg.Wait()
    fmt.Println(len(counter)) // 1000
}

In summary: the original code contains data races and incorrect capturing of variable i, which will lead to errors and unpredictable results.

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