临界区又叫关键代码段.在多线程共享变量时,用来安全读写共享变量.代码如下:
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);//删除临界区 }
本文转自Chinayu201451CTO博客,原文链接:http://blog.51cto.com/9233403/2048966 ,如需转载请自行联系原作者