Go Mutex and RWMutex

From NovaOrdis Knowledge Base
Revision as of 03:29, 20 January 2024 by Ovidiu (talk | contribs) (→‎Mutex)
Jump to navigation Jump to search

External

Internal

Overview

Mutex

https://pkg.go.dev/sync#Mutex

A Mutex is a mutual exclusion lock that can be used to ensure synchronized access to a critical section of the program. A Mutex shares memory by creating a convention developers must follow to synchronize access to memory. The developers are responsible for guarding access to memory in the program. From that perspective, channel-based concurrency model is preferred, unless there are valid reasons to use the Mutex.

The Mutex is implemented as a binary semaphore. Only one goroutine can enter the critical section at a time. Not until the call to the Unlock() function issued can another goroutine enter the critical section.

var mutex sync.Mutex

...

mutex.Lock() 

// do something in a mutual exclusion mode

mutex.Unlock()

Methods

Lock()

The goroutine should call Lock() before it is about to use the shared data. If nobody called Lock() before, the call will proceed and the calling goroutine will acquire the lock. If somebody else has the lock, the call will block. Multiple threads may potentially block on the same lock. Lock() ensures that only one thread can be in the mutually exclusion region.

Unlock()

The goroutine that is done using the shared data should call Unlock(). If other threads are waiting on the lock, one of the threads will be unblocked and will be able to continue. A mutex that was not locked raises a panic on an attempt to unlock:

fatal error: sync: unlock of unlocked mutex

RWMutex

https://pkg.go.dev/sync#RWMutex

A RWMutex is a mutual exclusion lock that allows differentiated access to readers and writers.

Patterns

Call Unlock() with defer

Locking a mutex at the top of a method and immediately invoking the unlocking method with defer is a very common idiom:

var lock Mutex
func someFunc() {
  lock.Lock()
  defer lock.Unlock()
  ...
}

This ensures that that the unlocking calls always happen, even for panic.

Guarding the Internal State of a struct

Guarding the internal state of a struct is is one of the not very numerous patterns where a sync primitive is actually recommended. This pattern defines the scope of atomicity for the SomeType type. Calls to something() can be considered atomic. By using memory access synchronization primitives, you can hide the implementation details of locking of your critical section from the callers. The keyword here is "internal". If you find yourself exposing logs beyond a type, this should raise a red flag. Try to keep the locks constrained to the smallest possible lexical scope.

type SomeType struct {
  name string
  ...
  sync.RWMutex
}

func (s * SomeType) something() {
  s.Lock()
  defer s.Unlock()
}