Sobes.tech
Senior

What synchronization primitives are available in Go? How does RWMutex differ from a regular Mutex?

sobes.tech AI

Answer from AI

In Go, synchronization primitives from the sync package are used, the main ones are:

  • Mutex — a regular mutex for mutual exclusion, blocks access to the resource for all other goroutines until it is unlocked.
  • RWMutex — a mutex with read and write separation. Allows multiple goroutines to read data simultaneously (RLock), but writing (Lock) is exclusive and blocks everyone.
  • WaitGroup — for waiting for a group of goroutines to finish.
  • Cond — a condition variable for signaling between goroutines.

Difference between RWMutex and Mutex:

  • Mutex fully blocks access, allowing only one owner.
  • RWMutex allows multiple readers to hold the lock simultaneously if there are no writers.
  • Writing with RWMutex is exclusive and blocks others.

Example:

var mu sync.RWMutex
var data int

func readData() int {
    mu.RLock()         // lock for reading
    defer mu.RUnlock()
    return data
}

func writeData(val int) {
    mu.Lock()          // exclusive lock for writing
    defer mu.Unlock()
    data = val
}

Using RWMutex improves performance in scenarios with frequent reads and infrequent writes.