refactor: reorganize docs into plan/ and add skills/
This commit is contained in:
46
docs/api/threading/threading-spinlock.md
Normal file
46
docs/api/threading/threading-spinlock.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# SpinLock
|
||||
|
||||
**命名空间**: `XCEngine::Threading`
|
||||
|
||||
**类型**: `class`
|
||||
|
||||
**描述**: 自旋锁封装类,使用原子操作实现,适用于保护极短的临界区。
|
||||
|
||||
## 概述
|
||||
|
||||
`SpinLock` 是一个轻量级的自旋锁实现,使用 `std::atomic_flag` 的 test-and-set 操作。它在获取锁失败时不断轮询,不会导致线程切换,非常适合保护非常短的临界区(如简单的计数器递增)。
|
||||
|
||||
## 公共方法
|
||||
|
||||
| 方法 | 描述 |
|
||||
|------|------|
|
||||
| `void Lock()` | 获取锁(忙等待) |
|
||||
| `void Unlock()` | 释放锁 |
|
||||
| `bool TryLock()` | 尝试获取锁(非阻塞) |
|
||||
|
||||
## 使用示例
|
||||
|
||||
```cpp
|
||||
Threading::SpinLock spinLock;
|
||||
int counter = 0;
|
||||
|
||||
// 保护极短的临界区
|
||||
void FastIncrement() {
|
||||
spinLock.Lock();
|
||||
++counter; // 单一操作,无需切换到内核
|
||||
spinLock.Unlock();
|
||||
}
|
||||
|
||||
// TryLock 用法
|
||||
void SafeIncrement() {
|
||||
if (spinLock.TryLock()) {
|
||||
++counter;
|
||||
spinLock.Unlock();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [Mutex](./threading-mutex.md) - 互斥锁
|
||||
- [ReadWriteLock](./threading-readwritelock.md) - 读写锁
|
||||
Reference in New Issue
Block a user