Files
XCEngine/docs/api/threading/spinlock/spinlock.md
ssdfasd 7dd7858ef2 docs: fix threading module documentation discrepancies
- Fix SpinLock docs: clarify lock()/unlock()/try_lock() are non-const
  (matching source implementation in SpinLock.h)
- Add missing LambdaTask::Execute() method to inherited methods table
- Update TaskGroup::Wait() docs: clarify m_pendingCount never decrements
  causing indefinite block even after all tasks complete (not just
  unexecuted tasks)
- Update TaskGroup::IsComplete() docs: document same m_pendingCount
  issue causing incorrect return values
2026-03-19 01:03:14 +08:00

1.3 KiB

SpinLock

命名空间: XCEngine::Threading

类型: class

头文件: XCEngine/Threading/SpinLock.h

描述: 自旋锁封装类,使用原子操作实现,适用于保护极短的临界区。

概述

SpinLock 是一个轻量级的自旋锁实现,使用 std::atomic_flag 的 test-and-set 操作。它在获取锁失败时不断轮询,不会导致线程切换,非常适合保护非常短的临界区(如简单的计数器递增)。

公共方法

方法 描述
Lock 获取锁(忙等待)
Unlock 释放锁
TryLock 尝试获取锁(非阻塞)

STL 兼容方法

支持 lock(), unlock(), try_lock() 以兼容 STL 的 lockable 概念。注意:这些方法为非 const 成员函数。

使用示例

Threading::SpinLock spinLock;
int counter = 0;

// 保护极短的临界区
void FastIncrement() {
    spinLock.Lock();
    ++counter;
    spinLock.Unlock();
}

// TryLock 用法
void SafeIncrement() {
    if (spinLock.TryLock()) {
        ++counter;
        spinLock.Unlock();
    }
}

相关文档