SRWLOCK g_lock = {}; //轻量级锁 CONDITION_VARIABLE g_val={};//轻量级锁的同步条件 INT iGlobal = 0; //读写的全局变量 DWORD WINAPI WriteThread(LPVOID lpParameter) {//写线程 while (1) { Sleep(20); __try { AcquireSRWLockExclusive(&g_lock);//申请独占锁 iGlobal++; } __finally { ReleaseSRWLockExclusive(&g_lock);//释放独占锁 WakeAllConditionVariable(&g_val);//唤醒条件变量 } } return 0; } DWORD WINAPI ReadThread(LPVOID lpParameter) {//读线程 while (true) { Sleep(30); __try { AcquireSRWLockShared(&g_lock);//申请共享锁 BOOL rt = SleepConditionVariableSRW(&g_val, &g_lock, 20, CONDITION_VARIABLE_LOCKMODE_SHARED);//等待条件变量 if (rt) { char str[20] = {}; itoa(iGlobal, str, 10); TRACE(str); } else { char str[20] = {}; itoa(iGlobal, str, 10); TRACE(str); } } __finally { ReleaseSRWLockShared(&g_lock);//释放锁 } } return 0; } void CtestThreadDlg::OnBnClickedButton15() { InitializeSRWLock(&g_lock); InitializeConditionVariable(&g_val); DWORD ThreadID =0; HANDLE hWrite = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WriteThread, NULL, CREATE_SUSPENDED, &ThreadID); HANDLE hRead = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadThread, NULL, CREATE_SUSPENDED, &ThreadID); ResumeThread(hWrite); ResumeThread(hRead); }
网页名称:线程间使用SRW轻量级锁共享变量
网页路径:https://www.cdcxhl.com/article18/johedp.html
成都网站建设公司_创新互联,为您提供品牌网站制作、品牌网站建设、网站收录、搜索引擎优化、外贸建站、网站营销
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联