Sobes.tech
Middle — Senior

Thread-safe output of unique elements from an array using a map

livecode

Task condition

It is necessary to modify the program so that:

  • only unique numbers are output from the slice nums;
  • a map is used to check for uniqueness;
  • the solution works correctly in a multithreaded environment with goroutines.
package main

import (
    "log"
    "sync"
)

func main() {
    nums := []int{3, 3, 2, 1, 2, 1, 1, 2, 4}
    var uniqMap = make(map[int]struct{})
    var mu sync.Mutex
    var wg sync.WaitGroup

    for _, num := range nums {
        wg.Add(1)
        go func(n int) {
            defer wg.Done()
            mu.Lock()
            if _, ok := uniqMap[n]; ok {
                mu.Unlock()
                return
            }
            uniqMap[n] = struct{}{}
            mu.Unlock()
            log.Println(n)
        }(num)
    }
    wg.Wait()
}