2026-03-20 02:35:24 +08:00
|
|
|
|
# Mutex::lock
|
|
|
|
|
|
|
|
|
|
|
|
```cpp
|
|
|
|
|
|
void lock() const;
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
获取互斥锁(const 版本)。如果锁已被其他线程持有,则阻塞当前线程直到锁可用。
|
|
|
|
|
|
|
|
|
|
|
|
该方法是 `std::lockable` 接口的实现,可与 `std::lock_guard`、`std::unique_lock` 等 RAII 工具配合使用。
|
|
|
|
|
|
|
|
|
|
|
|
**参数:** 无
|
|
|
|
|
|
|
|
|
|
|
|
**返回:** 无
|
|
|
|
|
|
|
|
|
|
|
|
**线程安全:** ✅
|
|
|
|
|
|
|
|
|
|
|
|
**复杂度:** 平均 O(1),最坏情况 O(n),n 为竞争线程数
|
|
|
|
|
|
|
|
|
|
|
|
**示例:**
|
|
|
|
|
|
|
|
|
|
|
|
```cpp
|
|
|
|
|
|
#include "XCEngine/Threading/Mutex.h"
|
|
|
|
|
|
#include <mutex>
|
|
|
|
|
|
|
2026-03-26 01:59:14 +08:00
|
|
|
|
XCEngine::Threading::Mutex mtx;
|
2026-03-20 02:35:24 +08:00
|
|
|
|
int counter = 0;
|
|
|
|
|
|
|
|
|
|
|
|
void Increment() {
|
|
|
|
|
|
mtx.lock();
|
|
|
|
|
|
++counter;
|
|
|
|
|
|
mtx.unlock();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 使用 RAII 自动管理锁
|
|
|
|
|
|
void SafeIncrement() {
|
|
|
|
|
|
std::lock_guard<XCEngine::Threading::Mutex> guard(mtx);
|
|
|
|
|
|
++counter;
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## 相关文档
|
|
|
|
|
|
|
|
|
|
|
|
- [Mutex 总览](mutex.md) - 返回类总览
|