Sobes.tech
Junior — Middle

Kas on võimalik tagada turvalisus, kirjutades Map-i samal ajal mitmest lõimest?

sobes.tech AI

Vastus AI-lt

In Go, the standard map (map) is not safe for concurrent writes from multiple goroutines. If multiple goroutines write to a map simultaneously without synchronization, it will cause a panic.

To ensure safety during concurrent writes, you can:

  • Use a mutex (sync.Mutex or sync.RWMutex) to protect access to the map.
  • Use specialized thread-safe data structures, such as sync.Map, designed for concurrent access.

Example with mutex:

var mu sync.Mutex
var m = make(map[string]int)

func safeWrite(key string, value int) {
    mu.Lock()
    defer mu.Unlock()
    m[key] = value
}

Or use sync.Map:

var m sync.Map

func safeWrite(key string, value int) {
    m.Store(key, value)
}

Thus, for safety during concurrent writes, synchronization must be used.