VLink  2.0.0
A high-performance communication middleware
spin_lock.h 文件参考

Cache-line aligned adaptive spin lock with exponential back-off. 更多...

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

浏览源代码.

class  vlink::SpinLock
 Adaptive spin lock satisfying the C++ Lockable named requirement. 更多...
 
class  vlink::SpinLockGuard
 RAII wrapper that locks a SpinLock on construction and unlocks on destruction. 更多...
 

命名空间

 

详细描述

Cache-line aligned adaptive spin lock with exponential back-off.

vlink::SpinLock is a user-space mutex aimed at very short critical sections (a few instructions) where a std::mutex context switch would dominate the cost. It is used inside CpuProfiler and other hot-path internals.

The acquisition loop applies exponential back-off so contention does not saturate the cache-coherence bus. Each back-off ladder rung doubles the inner spin budget until the cap is reached, then a CPU-pause instruction yields the core; once the total spin count exceeds the hard ceiling the back-off action switches to a sleep:

*   round 1   | XXXX---- 8 spins   ----> yield_cpu()
*   round 2   | XXXX-XXX 16 spins  ----> yield_cpu()
*   round 3   | XXXXXXXX 32 spins  ----> yield_cpu()
*   ...       |         ... up to 1024 spins per ladder rung
*   total > 50000 spins            ----> sleep_for(10 us)  (latched warn-once)
* 

Comparison with std::mutex:

Property SpinLock std::mutex
Wait strategy Adaptive busy-spin + yield + sleep OS futex / kernel wait
Critical-section Single-digit microseconds Any duration
Recursive No (deadlocks on re-entry) Use std::recursive_mutex
False sharing Avoided via alignas(64) Implementation defined
Header-only Yes (no VLINK_EXPORT) Library symbol
注解
  • The lock is non-recursive; double-locking from the same thread spins forever.
  • The hard-ceiling warning is latched per instance so a permanently contended lock does not flood the log.
Example
lock.lock();
critical_section();
lock.unlock();
{
vlink::SpinLockGuard guard(lock);
critical_section();
}