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

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.

Value Meaning
WAIT_ABANDONED The 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_0 The state of the specified object is signaled.
WAIT_TIMEOUT The 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操作,实际上是计数器减一。

阅读更多
个人分类: VC/MFC
上一篇关于socket编程
下一篇多线程编程小结
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭