互锁函数 (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;   
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值