您好,登錄后才能下訂單哦!
臨界區又叫關鍵代碼段.在多線程共享變量時,用來安全讀寫共享變量.代碼如下:
CRITICAL_SECTION g_csSync = {};//臨界區 INT g_iData = 0; DWORD WINAPI WriteThreadProc(LPVOID lpParameter) {//寫線程 while (1) { Sleep(30); __try { EnterCriticalSection(&g_csSync); g_iData++; } __finally { LeaveCriticalSection(&g_csSync); } } return 0; } DWORD WINAPI ReadThreadProc(LPVOID lpParameter) {//讀線程 while (true) { Sleep(30); __try { EnterCriticalSection(&g_csSync);//進入臨界區 char str[20] = {}; itoa(g_iData, str, 10); TRACE(str); } __finally { LeaveCriticalSection(&g_csSync);//離開臨界區 } } return 0; } void CtestThreadDlg::OnBnClickedButton16() { InitializeCriticalSectionAndSpinCount(&g_csSync, 0x4000);//初始化臨界區 DWORD ThreadID = 0; HANDLE hThread[2] = {}; hThread[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WriteThreadProc, NULL, CREATE_SUSPENDED, &ThreadID); hThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadThreadProc, NULL, CREATE_SUSPENDED, &ThreadID); ResumeThread(hThread[0]); ResumeThread(hThread[1]); WaitForMultipleObjects(2, hThread, TRUE, INFINITE); CloseHandle(hThread[0]); CloseHandle(hThread[1]); DeleteCriticalSection(&g_csSync);//刪除臨界區 }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。