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); }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。