Files
XCEngine/docs/api/threading/spinlock/spinlock.md
ssdfasd f427699ac6 refactor: improve test infrastructure and fix OpenGL GLAD initialization
- Rename D3D12Enum.h to D3D12Enums.h for naming consistency
- Fix OpenGL unit test GLAD initialization by using gladLoadGL()
  instead of gladLoadGLLoader(wglGetProcAddress) for fallback support
- Migrate remaining tests to use gtest_discover_tests for granular
  test discovery (math, core, containers, memory, threading, debug,
  components, scene, resources, input, opengl)
- Remove obsolete TEST_RESOURCES_DIR and copy_directory commands
  from OpenGL unit test CMakeLists (minimal/Res doesn't exist)
- Update TEST_SPEC.md with performance metrics and per-module
  build/test commands for faster development workflow
- Update CMake path references to use lowercase paths
2026-03-23 00:43:02 +08:00

1.4 KiB

SpinLock

命名空间: XCEngine::Threading

类型: class

头文件: XCEngine/Threading/SpinLock.h

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

概述

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

公共方法

方法 描述
Lock 获取锁(忙等待)
Unlock 释放锁
TryLock 尝试获取锁(非阻塞)
lock STL 兼容的 Lock
unlock STL 兼容的 Unlock
try_lock STL 兼容的 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();
    }
}

相关文档