Sobes.tech
Senior

Millised konkurentsi ligipääsu probleemid tekivad, kutsudes Get ja Set meetodeid erinevatest gorutinidest? Kuidas neid lahendada?

sobes.tech AI

Vastus AI-lt

When the Get and Set methods are called 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 in Go, the following are commonly used:

  • Mutex (sync.Mutex) — blocks access to data during the operation, ensuring exclusive access.
  • RWMutex (sync.RWMutex) — allows multiple goroutines to read data simultaneously but blocks writing if someone is writing.
  • Channels (channels) — organize 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()         // read lock
    defer m.mu.RUnlock()
    val, ok := m.data[key]
    return val, ok
}

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

This approach ensures that data is not corrupted during concurrent access.