Sobes.tech
Senior

What concurrency issues arise when calling Get and Set methods from different goroutines? How can they be resolved?

sobes.tech AI

Answer from AI

When calling the Get and Set methods simultaneously from different goroutines, a data race problem occurs. This happens because multiple goroutines can read and modify shared data at the same time, leading to unpredictable behavior and errors.

To solve this problem, Go typically uses:

  • Mutexes (sync.Mutex) — lock access to data during an operation, ensuring exclusive access.
  • RWMutex (sync.RWMutex) — allows multiple goroutines to read data simultaneously but blocks writing if someone is writing.
  • Channels — for organizing sequential access to data through message passing.

Example using RWMutex:

import "sync"

type SafeMap struct {
    mu sync.RWMutex
    data map[string]string
}

func (m *SafeMap) Get(key string) (string, bool) {
    m.mu.RLock()         // lock for reading
    defer m.mu.RUnlock()
    val, ok := m.data[key]
    return val, ok
}

func (m *SafeMap) Set(key, value string) {
    m.mu.Lock()          // lock for writing
    defer m.mu.Unlock()
    m.data[key] = value
}

This approach guarantees that data will not be corrupted during concurrent access.

What concurrency issues arise when calling Get and… - sobes.tech