CRITICAL_SECTION //critical_section 落日映苍穹つ 2022-08-20 14:16 174阅读 0赞 /// 关键代码段或是临界区的声明 CRITICAL\_SECTION g\_cs; unsigned \_\_stdcall PrintThread1( PVOID pvParm ) \{ /// 当前线程号 volatile static long lTreadNum = 0; int iCurThread = InterlockedIncrement( &lTreadNum ); for( int i = 0; i < 20; ++ i) \{ /// 进入临界区 EnterCriticalSection(&g\_cs); /// 对需要保护的资源进行操作 cout << "线程" << iCurThread << "打印:" << i << endl; /// 没此进入临界区后必须调用离开临界区函数 LeaveCriticalSection(&g\_cs); \} return 0; \} /// 使用TryEnterCriticalSection在获取资源不成功时会立刻返回,这时可以进行一些其它的操作后,再尝试进入 unsigned \_\_stdcall PrintThread2( PVOID pvParm ) \{ volatile static long lTreadNum = 0; int iCurThread = InterlockedIncrement( &lTreadNum ); /// 记录尝试进入临界区的次数 int iTryEnterTimes = 0; for( int i = 0; i < 20; ++ i) \{ /// 进入临界区不成功时,尝试次数加1 while( !TryEnterCriticalSection(&g\_cs) ) \{ \++iTryEnterTimes; \} cout << "线程" << iCurThread << "打印:" << i << " TryTimes:" << iTryEnterTimes << endl; iTryEnterTimes = 0; LeaveCriticalSection(&g\_cs); \} return 0; \} /// 启动线程并等待线程返回的函数 void StartThread( unsigned int (\_\_stdcall \* ThreadFuc)( void \*) ) \{ HANDLE hThread1 = (HANDLE)\_beginthreadex(NULL, 0, ThreadFuc, NULL, 0, NULL); HANDLE hThread2 = (HANDLE)\_beginthreadex(NULL, 0, ThreadFuc, NULL, 0, NULL); if( hThread1 != NULL ) \{ WaitForSingleObject(hThread1, INFINITE); CloseHandle(hThread1); \} if( hThread2 != NULL ) \{ WaitForSingleObject(hThread2, INFINITE); CloseHandle(hThread2); \} \} int \_tmain(int argc, \_TCHAR\* argv\[\]) \{ /// 在使用临界区前,必须进行初始化 InitializeCriticalSection(&g\_cs); StartThread( PrintThread1 ); cout << endl << endl; StartThread( PrintThread2 ); /// 使用完后,显示删除以避免资源泄漏 DeleteCriticalSection(&g\_cs); cout << endl << endl; /// 使用旋转锁初始化临界区,可以提高资源使用效率,尽可能使用这种方式进行资源保护 InitializeCriticalSectionAndSpinCount( &g\_cs, 400); StartThread( PrintThread1 ); DeleteCriticalSection(&g\_cs); return 0; \}
相关 线程同步:CriticalSection关键区域 \include <Windows.h> \include <iostream> using namespace std; DWORD WINAPI Func1Proc( LP 梦里梦外;/ 2022年08月06日 06:12/ 0 赞/ 193 阅读
相关 线程同步 -事件Event、临界区对象CriticalSection 事件Event: 基本函数: 全局对象:HANDLE g\_hEvent 创建事件对象:g\_hEvent=CreateEvent(NULL,FALSE,FALSE 忘是亡心i/ 2021年11月04日 13:02/ 0 赞/ 333 阅读
相关 C++多线程同步之临界区(CriticalSection) C++多线程同步之临界区(CriticalSection) 一、Win32平台 1、相关头文件和接口 \include <windows.h> CRITIC 以你之姓@/ 2021年09月21日 05:22/ 0 赞/ 378 阅读
还没有评论,来说两句吧...