WaitForSingleObject等待一个mutex句柄时的返回值
来源:互联网 发布:七天网络阅卷学生查分 编辑:程序博客网 时间:2024/05/22 05:04
今天遇到了用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,说明锁获取前没有被之前占有的线程(该线程本身已经退出,如果没有退出,则主线程在正常等待的时间里不会有返回值)正确释放。
- WaitForSingleObject等待一个mutex句柄时的返回值
- WaitForSingleObject 等待线程句柄
- WaitForSingleObject 等待线程句柄
- 主线程使用WaitForSingleObject和MsgWaitForMultipleObjects等待线程返回值
- Win32多线程之等待一个线程的结束(WaitForSingleObject)
- 为什么Mutex,Event,Thread句柄都是可以waitforsingleobject?
- c#线程同步中的lock,monitor,同步事件和等待句柄以及mutex的介绍
- C# 多线程(lock,Monitor,Mutex,同步事件和等待句柄)
- 线程句柄作WaitForSingleObject的参数是什么意思?
- 线程句柄作WaitForSingleObject的参数是什么意思?
- 线程句柄作WaitForSingleObject的参数是什么意思?
- Ajax等待返回结果时,弹出一个友好的等待提示
- Ajax等待返回结果时,弹出一个友好的等待提示
- 说说WaitForSingleObject可以等待的HANDLE
- 等待线程结束的高手--WaitForSingleObject
- WaitForSingleObject等待的时间精度测试
- mutex 与 WaitForSingleObject
- 等待句柄
- ulimit
- Chapter4-Cocos2dx学习资料
- 关于Cocos2d-x2.1.x与CocosBuilder3.0a 的自动资源目录摆放
- Ghost备份还原系统各选项作用
- 关于spfa的初步探究
- WaitForSingleObject等待一个mutex句柄时的返回值
- AntiXss 类库简介
- OO,OO以后,及其极限
- 关于三极管的"放大"作用
- 关于没有commit的死锁问题
- Using exchange server to send email in Powershell
- 无法找到“XXX.exe”的调试信息,或者调试信息不匹配
- iphone推送总结
- 获取JDBC中的ResultSet的记录的条数