Sobes.tech
Junior — Middle

How can you safely write to the same Map from multiple goroutines without using locks like Mutex?

sobes.tech AI

Answer from AI

In Go, to safely write to a shared Map from multiple goroutines without using Mutex, you can use specialized structures or approaches that ensure thread safety.

Main options:

  1. Using sync.Map — a built-in thread-safe implementation of Map in the sync package.
var m sync.Map

// Write
m.Store("key", "value")

// Read
value, ok := m.Load("key")
  1. Using channels for sequential access to the Map through a dedicated goroutine.
type request struct {
    key string
    val string
    done chan bool
}

func mapManager(reqCh <-chan request) {
    m := make(map[string]string)
    for req := range reqCh {
        m[req.key] = req.val
        req.done <- true
    }
}

// In other goroutines, send write requests via the channel

This way, lock usage is avoided, and access to the Map is serialized through the channel.

  1. Using atomic operations and copying — suitable for specific cases, but generally more complex.

It is recommended to use sync.Map for simplicity and efficiency unless there are special requirements for the data structure.

How can you safely write to the same Map from… - sobes.tech