Sobes.tech
Senior

What is the difference between Mutex and RWMutex?

sobes.tech AI

Answer from AI

Mutex and RWMutex are synchronization mechanisms in Go for managing access to shared resources.

  • Mutex (mutual exclusion) allows only one goroutine to hold the lock at a time. All other goroutines wait until the lock is released.

  • RWMutex (read-write mutex) divides the lock into two parts: for reading and for writing. Multiple goroutines can hold the read lock simultaneously (shared lock), but writing requires exclusive access (exclusive lock). This improves performance when there are many read operations and few writes.

Example of using RWMutex:

type SafeCounter struct {
    mu sync.RWMutex
    count int
}

func (c *SafeCounter) Read() int {
    c.mu.RLock()         // read lock
    defer c.mu.RUnlock()
    return c.count
}

func (c *SafeCounter) Write(val int) {
    c.mu.Lock()          // exclusive lock for writing
    defer c.mu.Unlock()
    c.count = val
}