Sobes.tech
Junior — Senior

Optimization and fixing concurrent access to the map

livecode

Task condition

It is necessary to improve the provided code by eliminating potential issues during concurrent writes to a shared data structure.

func main() {
    m := map[string]int{
        "one":    1,
        "two":    2,
        "three":  3,
        "four":   4,
    }

    for key := range m {
        key := key
        go func() {
            time.Sleep(time.Millisecond * 100)
            m[key]++
        }()
    }

    fmt.Println("Map after writes:", m)
}