你可以在需要保护的代码块中添加具体的逻辑。以下是一个示例,其中有两个线程执行过程:
#include <Windows.h>
#include <iostream>
// 定义全局变量 g_cs 作为临界区域
CRITICAL_SECTION g_cs;
DWORD WINAPI ThreadProc(LPVOID lpParam) {
EnterCriticalSection(&g_cs);
std::cout << "Thread " << GetCurrentThreadId() << " entered critical section." << std::endl;
// 这里是需要保护的代码块
for (int i = 0; i < 5; ++i) {
Sleep(1000); // 模拟耗时操作
std::cout << "Thread " << GetCurrentThreadId() << ": Iteration " << i + 1 << std::endl;
}
LeaveCriticalSection(&g_cs);
std::cout << "Thread " << GetCurrentThreadId() << " left critical section." << std::endl;
return 0;
}
int main() {
InitializeCriticalSection(&g_cs);
HANDLE hThread1, hThread2;
// 创建两个线程
hThread1 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
// 等待线程结束
WaitForSingleObject(hThread1, INFINITE);
WaitForSingleObject(hThread2, INFINITE);
CloseHandle(hThread1);
CloseHandle(hThread2);
DeleteCriticalSection(&g_cs);
return 0;
}
在这个示例中,两个线程将会交替进入临界区域,并输出相应的信息。你可以根据具体需求在代码块中进行适当的操作。
内容由零声教学AI助手提供,问题来源于学员提问




