您好,登錄后才能下訂單哦!
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); }
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。