Windows下的临界写法
#include <windows.h>
class CriticalSection {
public:
CriticalSection() {
InitializeCriticalSection(&cs_);
}
~CriticalSection() {
DeleteCriticalSection(&cs_);
}
// 辅助 Guard 类实现自动加锁/解锁
class Guard {
public:
explicit Guard(CriticalSection& cs) : cs_(cs) {
EnterCriticalSection(&cs_.cs_);
}
~Guard() {
LeaveCriticalSection(&cs_.cs_);
}
// 禁用拷贝与移动
Guard(const Guard&) = delete;
Guard& operator=(const Guard&) = delete;
private:
CriticalSection& cs_;
};
private:
CRITICAL_SECTION cs_;
// 禁用拷贝与移动
CriticalSection(const CriticalSection&) = delete;
CriticalSection& operator=(const CriticalSection&) = delete;
};
怎么用呢?
// 全局共享资源与临界区
CriticalSection g_cs;
int g_sharedData = 0;
void ThreadFunction() {
for (int i = 0; i < 1000; ++i) {
CriticalSection::Guard lock(g_cs); // 自动加锁
++g_sharedData; // 临界区操作
} // 自动解锁
}
int main() {
HANDLE threads[2];
threads[0] = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)ThreadFunction, nullptr, 0, nullptr);
threads[1] = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)ThreadFunction, nullptr, 0, nullptr);
WaitForMultipleObjects(2, threads, TRUE, INFINITE);
CloseHandle(threads[0]);
CloseHandle(threads[1]);
std::cout << "Final value: " << g_sharedData << std::endl; // 正确输出 2000
return 0;
}