利用互斥对象实现线程同步

1、关于WaitForSingleObject的返回值

If the function succeeds, the return value indicates the event that caused the function to return. This value can be one of the following.

ValueMeaning
WAIT_ABANDONEDThe specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread, and the mutex is set to nonsignaled.
WAIT_OBJECT_0The state of the specified object is signaled.
WAIT_TIMEOUTThe time-out interval elapsed, and the object's state is nonsignaled.

If the function fails, the return value is WAIT_FAILED. To get extended error information, call GetLastError.

第一种情况是如果某一个线程终止时,还有没有释放的mutex,则操作系统会自动将该mutex的线程id和计数器归零,设置为无信号状态(因为操作系统它维护了 线程信息和相关的互斥对象的信息),此时WaitForSingleObject返回WAIT_ABANDONED;第二种情况是典型的设置mutex为有信号状态;第三种情况是超时之后,mutex被设置为无信号状态。

2、关于CreateMutex函数返回值

If the function succeeds, the return value is a handle to the mutex object. If the named mutex object existed before the function call, the function returns a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS. Otherwise, the caller created the mutex.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

所以可以通过CreateMutex的返回值通过mutex来判断应用程序只能有一个实例在运行:
    hMutex = CreateMutex(NULL, FALSE, "ticket");
    if (hMutex)
    {
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
            cout<<"This program only can have one instance!"<<endl;
            return 0;
        }
    }

3、关于mutex的杂项
mutex中包含一个线程id(标识当前拥有该互斥对象的线程)和一个计数器(用来指明该线程拥有的互斥对象的数目),mutex的ReleaseMutex函数操作有谁拥有谁是释放的原则,也就是哪个线程拥有mutex(该mutex的线程id设置为该线程),则一定要在该线程中通过ReleaseMutex函数释放该mutex才会成功。对于WaitForSingleObject函数也类似,先要检查请求mutex的线程id是否和此时拥有该mutex的线程id相等,如果不等,则为正常等待互斥mutex操作。如果相等,此时虽然mutex处于有信号状态,但WaitForSingleObject也会成功,并将该mutex的计数器加一,此时对于ReleaseMutex操作,实际上是计数器减一。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值