扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
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); }
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流