mutex互斥锁的运用

1 声明互斥对象

HANDLE hrtextmutex=NULL;

2 创建锁对象

hrtextmutex = ::CreateMutex(NULL, FALSE, _T("testmutex"));

3 线程函数中用到上面定义的互斥锁对象

DWORD WINAPI testmutextfun(LPVOID param)
{
    if (!hrtextmutex)
        return 2;
    DWORD dwCount = 0, dwWaitResult;
    int i = 0;
    while (i < 100)
    {
        dwWaitResult = WaitForSingleObject(hrtextmutex, INFINITE);
        switch (dwWaitResult)
        {
        case WAIT_OBJECT_0:// 成功等候有信号状态 
            __try{
                i++;
                char msg[200] = { 0 };
                sprintf_s(msg, 200, "\ntestmutextfun i=%d threadid=%d\n", i, ::GetCurrentThreadId());
                OutputDebugStringA(msg);
            }
            __finally{
                // 通过ReleaseMutex释放线程拥有的互斥对象所有权,如果不调用这语句,则其它线程获取时因状态丢失而无法获得所有权从而导致同步对象失败
                if (!ReleaseMutex(hrtextmutex))
                {
                    OutputDebugStringA("\nReleaseMutex error\n");
                }
            }
        
            break;
        case WAIT_ABANDONED: // 丢失状态 
            OutputDebugStringA("\nWaitForSingleObject abandoned\n");
            return FALSE;
            break;
        default:
            break;
        }
        
    }
    return TRUE;
}

4 创建2个线程对象,并关闭线程对象

HANDLE hrThreadArr[2] = { 0 };
    for (int i = 0; i < 2; i++)
    {
        hrThreadArr[i] = ::CreateThread(NULL, 0, testmutextfun, NULL, 0, NULL);
        if (NULL == hrThreadArr[i])
        {
            char msg[100] = { 0 };
            sprintf_s(msg, 100, "\ncreate thread failed errorcode:%d\n", GetLastError());
            OutputDebugStringA(msg);
            return;
        }
    }
    WaitForMultipleObjects(2, hrThreadArr, true, INFINITE);
    for (int i = 0; i < 2; i++)
    {
        CloseHandle(hrThreadArr[i]);
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值