Sobes.tech
Middle+

Does a regular mutex lock for both reading and writing?

sobes.tech AI

Answer from AI

A regular mutex (in Go, this is sync.Mutex) blocks access to the resource completely — both for reading and writing. That is, when the mutex is locked, no other goroutines can read or write the protected data.

If a lock is needed that allows multiple readers to read simultaneously but blocks writing, then sync.RWMutex is used. It has methods RLock/RUnlock for reading and Lock/Unlock for writing.

Example of using sync.Mutex:

var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}

Here, while one goroutine holds the lock, others wait, even if they only need to read.

Does a regular mutex lock for both reading and… - sobes.tech