WaitForSingleObject等待一个mutex句柄时的返回值

今天遇到了用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,说明锁获取前没有被之前占有的线程(该线程本身已经退出,如果没有退出,则主线程在正常等待的时间里不会有返回值)正确释放。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值