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);//删除临界区 }
原文地址:http://blog.51cto.com/9233403/2048966