Sobes.tech
Senior

// all elements of the slice should be unique + consist of 1000 elements in total // the program should not hang due to time.sleep func main() { checkIncrement := map[int]int32{} var data []int for i := 0; i < 1000; i++ { go func() { data = append(data, i) if _, found := checkIncrement[i]; found { fmt.Println(i) panic("duplicated increment") } checkIncrement[i] = 1 }() } time.Sleep(2 * time.Second) fmt.Println(len(data)) }

sobes.tech AI

Answer from AI

The provided code has several issues:

  • Concurrent access to the data slice and the checkIncrement map from multiple goroutines without synchronization leads to data races.
  • Using time.Sleep to wait for goroutines to finish is inefficient and unreliable.

To fix:

  • Use a mutex (sync.Mutex) to protect shared data.
  • Use sync.WaitGroup to wait for all goroutines to complete instead of time.Sleep.

Example of corrected code:

package main

import (
	"fmt"
	"sync"
)

func main() {
	checkIncrement := make(map[int]struct{})
	var data []int
	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()
			defer mu.Unlock()

			if _, found := checkIncrement[val]; found {
				panic(fmt.Sprintf("duplicated increment: %d", val))
			}

			checkIncrement[val] = struct{}{}
			data = append(data, val)
		}(i)
	}

	wg.Wait()
	fmt.Println("Length of data:", len(data))
}

This guarantees the uniqueness of elements, correct addition to the slice, and avoids using time.Sleep to wait.

// all elements of the slice should be unique +… - sobes.tech