Files
XCEngine/docs/api/threading/threading-mutex.md

52 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Mutex
**命名空间**: `XCEngine::Threading`
**类型**: `class`
**描述**: 互斥锁封装类,基于 `std::mutex` 实现,提供线程安全的互斥访问。
## 概述
`Mutex` 是对 `std::mutex` 的简单封装,提供了标准的 Lock/Unlock/TryLock 接口。它是 XCEngine 中最基础的同步原语,适用于保护共享数据的访问。
## 公共方法
| 方法 | 描述 |
|------|------|
| `void Lock()` | 获取锁(阻塞) |
| `void Unlock()` | 释放锁 |
| `bool TryLock()` | 尝试获取锁(非阻塞,成功返回 true |
## STL 兼容方法
支持 `lock()``unlock()``try_lock()` 以兼容 STL 的 lockable 概念。
## 使用示例
```cpp
Threading::Mutex mtx;
int sharedData = 0;
// 线程安全地修改共享数据
void SafeIncrement() {
mtx.Lock();
++sharedData;
mtx.Unlock();
}
// 或使用 TryLock
void SafeTryIncrement() {
if (mtx.TryLock()) {
++sharedData;
mtx.Unlock();
}
}
```
## 相关文档
- [SpinLock](./threading-spinlock.md) - 自旋锁
- [ReadWriteLock](./threading-readwritelock.md) - 读写锁
- [TaskSystem](./threading-task-system.md) - 任务系统