Go Mutex and RWMutex: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(40 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
=External=
* https://pkg.go.dev/sync#Mutex
 
=Internal=
=Internal=
* [[Go_Package_sync#Mutex|The <tt>sync</tt> package]]
* [[Go_Package_sync#Mutex|The <tt>sync</tt> package]]
Line 6: Line 6:


=Overview=
=Overview=
A <code>Mutex</code> is a [[Concurrent_(Parallel)_Programming#Mutual_Exclusion|mutual exclusion]] lock, implemented as a [[Concurrent_(Parallel)_Programming#Binary_Semaphore|binary semaphore]]. Only one goroutine can enter the critical section at a time. Not until the call to the <code>Unlock()</code> function issued can another goroutine enter the critical section.
=Mutex=
 
{{External|https://pkg.go.dev/sync#Mutex}}
The usage pattern follows, and the curly braces are not necessary, but can be used for clarity:
A <code>Mutex</code> is a [[Concurrent_(Parallel)_Programming#Mutual_Exclusion|mutual exclusion lock]] that can be used to ensure [[Concurrent_(Parallel)_Programming#Synchronized_Access|synchronized access]] to a [[Concurrent_(Parallel)_Programming#Critical_Section|critical section]] of the program. A <code>Mutex</code> 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 [[Go_Concurrency#Programming_Models|valid reasons]] to use the <code>Mutex</code>.


The <code>Mutex</code> is implemented as a [[Concurrent_(Parallel)_Programming#Binary_Semaphore|binary semaphore]]. Only one goroutine can enter the critical section at a time. Not until the call to the <code>Unlock()</code> function issued can another goroutine enter the critical section.
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
var mutex sync.Mutex
var mutex sync.Mutex
Line 15: Line 16:
...
...


mutex.Lock() {
mutex.Lock()  
    // do something in a mutual exclusion mode
 
// do something in a mutual exclusion mode
 
mutex.Unlock()
</syntaxhighlight>
==Methods==
===<tt>Lock()</tt>===
The goroutine should call <code>Lock()</code> before it is about to use the shared data. If nobody called <code>Lock()</code> 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. <code>Lock()</code> ensures that only one thread can be in the mutually exclusion region.
 
===<tt>Unlock()</tt>===
The goroutine that is done using the shared data should call <code>Unlock()</code>. 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:
<font size=-2>
fatal error: sync: unlock of unlocked mutex
</font>
==The <tt>sync.Locker</tt> Interface==
The <code>Lock()</code> and <code>Unlock()</code> are grouped together under the <code>sync.Locker</code> interface:
<syntaxhighlight lang='go'>
type Locker interface {
  Lock()
  Unlock()
}
</syntaxhighlight>
 
=RWMutex=
{{External|https://pkg.go.dev/sync#RWMutex}}
A <code>RWMutex</code> is a [[Concurrent_(Parallel)_Programming#Mutual_Exclusion|mutual exclusion lock]] that allows differentiated access to readers and writers. If the lock is requested for reading, it will be granted, unless the lock is being held for writing. An arbitrary number of readers can hold a reader lock. Only one writer can hold a writer lock.
=Reentrance=
<font color=darkkhaki>TODO</font>.
 
=Patterns=
==Call <tt>Unlock()</tt> with <tt>defer</tt>==
Locking a mutex at the top of a method and immediately invoking the unlocking method with <code>[[Go_Functions#defer_-_Deferred_Function_Calls|defer]]</code> is a very common idiom:
<syntaxhighlight lang='go'>
var lock Mutex
func someFunc() {
  lock.Lock()
  defer lock.Unlock()
  ...
}
</syntaxhighlight>
This ensures that that the unlocking calls always happen, even for <code>panic</code>.
 
==<span id='Extending_a_struct_with_a_Mutex'></span>Guarding the Internal State of a <tt>struct</tt>==
Guarding the internal state of a <code>struct</code> is is one of the not very numerous patterns where a <code>sync</code> primitive is [[Go_Concurrency#Guarding_the_Internal_State_of_a_struct|actually recommended]]. This pattern defines the [[Concurrent_(Parallel)_Programming#Atomicity|scope of atomicity]] for the <code>SomeType</code> type. Calls to <code>something()</code> 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.
<syntaxhighlight lang='go'>
type SomeType struct {
  name string
  ...
  sync.RWMutex
}
}


mutex.Unlock()
func (s * SomeType) something() {
  s.Lock()
  defer s.Unlock()
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 03:48, 20 January 2024

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

The sync.Locker Interface

The Lock() and Unlock() are grouped together under the sync.Locker interface:

type Locker interface {
  Lock()
  Unlock()
}

RWMutex

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

A RWMutex is a mutual exclusion lock that allows differentiated access to readers and writers. If the lock is requested for reading, it will be granted, unless the lock is being held for writing. An arbitrary number of readers can hold a reader lock. Only one writer can hold a writer lock.

Reentrance

TODO.

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()
}