CRITICAL_SECTION //critical_section

落日映苍穹つ 2022-08-20 14:16 264阅读 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;
}

发表评论

表情:
评论列表 (有 0 条评论,264人围观)

还没有评论,来说两句吧...

相关阅读