Files
XCSDD/docs/api/threading/spinlock/spinlock.md
ssdfasd 58a83f445a fix: improve doc link navigation and tree display
- Fix link resolution with proper relative/absolute path handling
- Improve link styling with underline decoration
- Hide leaf nodes from tree, only show directories
- Fix log file path for packaged app
2026-03-19 12:44:08 +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();
    }
}

相关文档