All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
spin_mutex Class Reference

#include <thread.h>


class  lock_guard

Public Member Functions

 spin_mutex (void) noexcept
 ~spin_mutex (void) noexcept
 spin_mutex (const spin_mutex &) noexcept
const spin_mutexoperator= (const spin_mutex &) noexcept
void lock () noexcept
void unlock () noexcept
bool try_lock () noexcept

Detailed Description

A spin_mutex is semantically equivalent to a regular mutex, except for the following:

  • A spin_mutex is just 1 byte, whereas a regular mutex is quite large (44 bytes for pthread).
  • A spin_mutex is extremely fast to lock and unlock, whereas a regular mutex is surprisingly expensive just to acquire a lock.
  • A spin_mutex takes CPU while it waits, so this can be very wasteful compared to a regular mutex that blocks (gives up its CPU slices until it acquires the lock).

The bottom line is that mutex is the usual choice, but in cases where you need to acquire locks very frequently, but only need to hold the lock for a very short period of time, you may save runtime by using a spin_mutex, even though it's non-blocking.

N.B. A spin_mutex is only the size of a bool. To avoid "false sharing", be careful not to put two spin_mutex objects on the same cache line (within 128 bytes of each other), or the two mutexes may effectively (and wastefully) lock against each other.

Definition at line 177 of file thread.h.

Constructor & Destructor Documentation

spin_mutex::spin_mutex ( void  )

Definition at line 179 of file thread.h.

spin_mutex::~spin_mutex ( void  )

Definition at line 180 of file thread.h.

spin_mutex::spin_mutex ( const spin_mutex )

Copy constructor – initialize to unlocked.

Definition at line 184 of file thread.h.

Member Function Documentation

void spin_mutex::lock ( )

Acquire the lock, spin until we have it.

Definition at line 192 of file thread.h.

const spin_mutex& spin_mutex::operator= ( const spin_mutex )

Assignment does not do anything, since lockedness should not transfer.

Definition at line 188 of file thread.h.

bool spin_mutex::try_lock ( )

Try to acquire the lock. Return true if we have it, false if somebody else is holding the lock.

Definition at line 235 of file thread.h.

void spin_mutex::unlock ( )

Release the lock that we hold.

Definition at line 227 of file thread.h.

The documentation for this class was generated from the following file: