Sobes.tech
Junior — Middle+

Getting Unique Array Values Using Goroutines

livecode

Task condition

It is required to use multiple goroutines to obtain only unique elements from a generated array, while excluding duplicate results and sending the found unique numbers to a channel. Proper synchronization of access to the shared storage of already encountered values must be ensured to avoid data races.

func main() {
    var seen = make(map[int]struct{})
    lock := sync.Mutex{}
    size := 1000

    numbers := make([]int, 0, size)
    for i := 0; i < size; i++ {
        numbers = append(numbers, rand.Intn(10)) // generate random ints
    }

    uniqChan := make(chan int, size)
    wg := sync.WaitGroup{}

    for i := 0; i < size; i++ {
        i := i
        wg.Add(1)
        go func() {
            defer wg.Done()
            if _, ok := seen[numbers[i]]; !ok {
                lock.Lock()
                seen[numbers[i]] = struct{}{}
                lock.Unlock()
                uniqChan <- numbers[i]
            }
        }()
    }

    wg.Wait()
    close(uniqChan)

    for val := range uniqChan {
        fmt.Println(val)
    }

    fmt.Println(uniqChan)
}