今天遇到了用WaitForSingleObject去等待一个Mutex句柄,对他的两个返回值(WAIT_OBJECT_0和WAIT_ABANDONED)含义有点含糊,于是写了测试代码模拟了下
根据msdn上的解释
WAIT_OBJECT_0:The state of the specified object is signaled.
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 state is set to nonsignaled.(等待的锁之前被其他线程占用,但该线程退出时没有正确释放锁)
If the mutex was protecting persistent state information, you should check it for consistency.
测试代码,线程的实现使用了ZThread库
#include <windows.h>
#include "FastLockTestThread.h"
#include "zthread/Thread.h"
using namespace ZThread;
HANDLE _hMutex = ::CreateMutex(0, 0, 0);
int main()
{
Thread t(new ThreadA());
Thread::sleep(2000);
DWORD dwWait = ::WaitForSingleObject(_hMutex, INFINITE);
if(dwWait == WAIT_ABANDONED)
{
std::cout<<"main thread can not get mutex"<<std::endl;
::ReleaseMutex(_hMutex);
}
return 0;
}
#pragma once
#include "zthread/Runnable.h"
#include <iostream>
class ThreadA : public ZThread::Runnable
{
public:
virtual void run()
{
extern HANDLE _hMutex;
if(::WaitForSingleObject(_hMutex, INFINITE) != WAIT_OBJECT_0)
{
}
else
{
std::cout<<"thread A get mutex"<<std::endl;
}
}
};
两个线程对全局锁_hMutex的竞争
主线程中启动了一个线程A,然后主线程休眠2秒(让线程A有足够的时间执行完),然后等待全局锁句柄_hMutex,此时线程A已经执行完,线程A的run方法中已经获取了全局锁的授权,然后退出,退出时没有释放锁,因此主线程在等待锁信号时返回了WAIT_ABANDONED,说明锁获取前没有被之前占有的线程(该线程本身已经退出,如果没有退出,则主线程在正常等待的时间里不会有返回值)正确释放。
本文通过测试代码详细解析了Mutex与WaitForSingleObject函数的使用,特别是WAIT_OBJECT_0与WAIT_ABANDONED返回值的区别。展示了当线程意外终止而未释放Mutex时的情况。
3万+

被折叠的 条评论
为什么被折叠?



