Sobes.tech
Middle

Milliseid mutex'e kasutate turvalisuse tagamiseks, töötades kaartidega Go keeles?

sobes.tech AI

Vastus AI-lt

To ensure safety when working with non-concurrent access to data structures, including maps (map), Go uses mutexes from the sync package.

  • sync.Mutex: Basic mutex for mutual exclusion. Used for locking and unlocking code sections where reading or writing to a map occurs.
  • sync.RWMutex: Mutex with shared (read) and exclusive (write) access. Allows multiple goroutines to read from the map simultaneously, but only one to write. Ideal for scenarios where reads significantly outnumber writes.

The preferred option for concurrent-safe map operations is sync.RWMutex, as it provides better performance with multiple simultaneous read operations.

Example of using sync.RWMutex:

import (
	"sync"
)

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

func NewSafeMap() *SafeMap {
	return &SafeMap{
		m: make(map[string]int),
	}
}

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

func (sm *SafeMap) Get(key string) (int, bool) {
	sm.mu.RLock()  // Lock for reading
	defer sm.mu.RUnlock()
	value, ok := sm.m[key]
	return value, ok
}

There is also a specialized type sync.Map, optimized for concurrent use without explicit mutex locking in most cases, but it has certain limitations and a different API. However, if more flexible control over locking or specific access scenarios are required, using sync.RWMutex over a standard map is a common practice.