本文主要是介绍互锁函数 (CRITICAL_SECTION)的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
http://blog.163.com/up_downdown/blog/static/1803443272011311912324/
CRITICAL_SECTION的使用
临界区使用
view plaincopy to clipboardprint
/// 关键代码段或是临界区的声明
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;
}
这篇关于互锁函数 (CRITICAL_SECTION)的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!