VLink 2.0.0
A high-performance communication middleware
Loading...
Searching...
No Matches
spin_lock.h File Reference

Adaptive, cache-line-aligned spin lock and RAII guard. More...

#include <algorithm>
#include <atomic>
#include <cstdint>
#include <thread>
#include "./logger.h"
#include "./macros.h"
#include "./utils.h"
Include dependency graph for spin_lock.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

 Adaptive, cache-line-aligned spin lock. More...
 RAII guard that acquires a SpinLock on construction and releases it on destruction. More...

Namespaces

Detailed Description

Adaptive, cache-line-aligned spin lock and RAII guard.

SpinLock implements a simple user-space mutex that spins instead of sleeping. It is intended for very short critical sections (a few CPU instructions) where the overhead of a std::mutex context switch would dominate. It is used inside CpuProfiler and other hot-path VLink internals.

Locking strategy inside lock():

  1. Try to acquire with exchange(true, acquire); if successful, return.
  2. Spin with load(relaxed) until the flag appears free, then retry.
  3. Apply exponential back-off: after every backoff spins, call Utils::yield_cpu() (a CPU-pause instruction).
  4. If kMaxSpinCount (50000) is exceeded, sleep for 10 us and log an error. This is a safety valve for pathological contention.

Cache-line alignment (alignas(64)) prevents false sharing when multiple SpinLock objects reside in adjacent memory.

Note
  • Do not use this lock for long critical sections or I/O – use a std::mutex instead.
  • SpinLock is not recursive; a thread that calls lock() twice will deadlock.
  • The lock is not VLINK_EXPORT because it is header-only and entirely inlined.
Example
// Manual lock/unlock:
lock.lock();
critical_section();
lock.unlock();
// RAII guard (preferred):
{
vlink::SpinLockGuard guard(lock);
critical_section();
} // automatically unlocked here