临界区又叫关键代码段.在多线程共享变量时,用来安全读写共享变量.代码如下:
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。