ZBLOG

// 定义全局变量 g_cs 作为临界区域 CRITICAL_SECTION g_cs; // 初始化临界区域 InitializeCriticalSection(&g_cs); // 加锁并进入临界区域 EnterCriticalSection(&g_cs); // 这里是需要保护的代码块 // ... LeaveCriticalSection(&g_cs); // 解锁 // 在不再需要使用临界区域时,释放资源 DeleteCriticalSection(&g_cs); 完善这部...

你可以在需要保护的代码块中添加具体的逻辑。以下是一个示例,其中有两个线程执行过程:

#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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8976

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?