VLink 2.0.0
A high-performance communication middleware
载入中...
搜索中...
未找到
spin_lock.h 文件参考

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

#include <algorithm>
#include <atomic>
#include <cstdint>
#include <thread>
#include "./logger.h"
#include "./macros.h"
#include "./utils.h"
spin_lock.h 的引用(Include)关系图:
此图展示该文件被哪些文件直接或间接地引用了:

浏览该文件的源代码.

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

命名空间

详细描述

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.

注解
  • 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