StuBS
Loading...
Searching...
No Matches
Spinlock Class Reference

Using Spinlocks, it is possible to serialize blocks of code that might otherwise run in parallel on multiple CPU cores, or be interleaved due to interrupts or scheduling. More...

#include <spinlock.h>

Public Member Functions

 Spinlock ()
 Constructor; Initializes as unlocked.
 
void lock ()
 Enters the critical area. In case the area is already locked, lock() will actively wait until the area can be entered.
 
void unlock ()
 Unblocks the critical area.
 

Detailed Description

Using Spinlocks, it is possible to serialize blocks of code that might otherwise run in parallel on multiple CPU cores, or be interleaved due to interrupts or scheduling.

Synchronization is implemented using a lock variable. Once a thread enters the critical area, it sets the lock variable (to a non-zero value); when this thread leaves the critical area, it resets the lock variable to zero. Threads trying to enter an already locked critical area, actively wait, continuously checking until the critical area is free again.

Use the following two GCC intrinsics

  • bool __atomic_test_and_set(void *ptr, int memorder)
  • void __atomic_clear (bool *ptr, int memorder)

These intrinsics are translated into atomic, architecture-specific CPU instructions.

If you want that things just work, choose __ATOMIC_SEQ_CST as memorder. This is not the most efficient memory order but works reasonably well.

Atomic Builtins in GCC manual


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