- 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
2.4 KiB
2.4 KiB
ReadWriteLock
命名空间: XCEngine::Threading
类型: class
头文件: XCEngine/Threading/ReadWriteLock.h
描述: 读写锁,允许多个读者或单个写者
概述
ReadWriteLock 实现了一个经典的读写锁。它允许多个线程同时持有读锁,但在有写锁时,所有读锁都必须释放,写锁为独占访问。这对于读操作远多于写操作的共享数据非常有效。
设计目的
- 提供比普通互斥锁更高的并发性能
- 允许多个线程同时读取共享数据
- 确保写入操作时的独占性访问
- 防止写者饥饿(通过写者优先策略)
使用场景
- 读多写少的共享数据访问
- 需要保护长时间读取的数据结构
- 数据库、缓存、配置等共享资源访问
公共方法
| 方法 | 描述 |
|---|---|
ReadWriteLock |
构造一个读写锁 |
~ReadWriteLock |
销毁读写锁 |
ReadLock |
获取读锁(支持多个并发读者) |
ReadUnlock |
释放读锁 |
WriteLock |
获取写锁(独占,阻塞所有读者和写者) |
WriteUnlock |
释放写锁 |
使用示例
#include "XCEngine/Threading/ReadWriteLock.h"
#include <thread>
#include <vector>
#include <iostream>
#include <map>
XCEngine::Threading::ReadWriteLock rwLock;
std::map<std::string, int> sharedCache;
// 读操作(多个线程可同时读)
int ReadData(const std::string& key) {
rwLock.ReadLock();
int value = 0;
auto it = sharedCache.find(key);
if (it != sharedCache.end()) {
value = it->second;
}
rwLock.ReadUnlock();
return value;
}
// 写操作(独占)
void WriteData(const std::string& key, int value) {
rwLock.WriteLock();
sharedCache[key] = value;
rwLock.WriteUnlock();
}
int main() {
std::vector<std::thread> threads;
threads.emplace_back(WriteData, "score", 100);
threads.emplace_back(ReadData, "score");
threads.emplace_back(WriteData, "health", 200);
threads.emplace_back(ReadData, "health");
for (auto& t : threads) {
t.join();
}
return 0;
}
相关文档
ReadLock- 获取读锁ReadUnlock- 释放读锁WriteLock- 获取写锁WriteUnlock- 释放写锁