摘要:同一个CMutex对象不允许在两个线程中分别调用Lock和Unlock,否则Unlock会失败并返回0。
一、问题描述
笔者最近在开发过程中遇到了CMutex::Unlock返回0的情况,通过MSDN得知这表示Unlock失败。但MSDN并没有告诉我为什么会失败以及如何处理,查百度谷歌亦无果,于是决定动手探索。
这是MSDN上Unlock对返回值的解释
The default implementation of the declaration with two parameters always returns TRUE. This function is called to release access to the synchronization object owned by the calling thread. The second declaration is provided for synchronization objects such as semaphores that allow more than one access of a controlled resource.
二、产生问题的原因
产生问题的原因如摘要所述:同一个CMutex对象不允许在两个线程中分别调用Lock和Unlock,否则Unlock会失败并返回0。(P.S.这可能并不是唯一会使Unlock返回0的原因,笔者这次是这个原因)
三、例程
1、源码
#include "stdafx.h" #include "stdlib.h" #include "afxmt.h" #include <iostream> using namespace std; CMutex g_objLock; DWORD WINAPI ThrdFun1(LPVOID lpParam)// { int iResult,iResult1,i=0,iTest; int iCount=0,iCycle=1; for(i=0;i<9999;i++) { g_objLock.Lock(); printf("ThrdFun1:%d\n",i); g_objLock.Unlock(); Sleep(1000); } return 0; } DWORD WINAPI ThrdFun2(LPVOID lpParam)// { int iResult,iResult1,i=0,iTest; int iCount=0,iCycle=1; int iSleep=5; /*printf("ThrdFun2:lock and sleep %d sec\n",iSleep); g_objLock.Lock(); Sleep(iSleep*1000);*/ iResult=g_objLock.Unlock(); printf("ThrdFun2:unlock ret %d\n",iResult); return 0; } int _tmain(int argc, _TCHAR* argv[]) { int iResult,iResult1,i=0,iTest; int iSleep=5; printf("start 1\n"); CreateThread(NULL, 0, ThrdFun1, NULL, 0, NULL); printf("sleep %d sec\n",iSleep); Sleep(iSleep*1000); printf("lock and sleep %d sec\n",iSleep); g_objLock.Lock(); Sleep(iSleep*1000); iResult=g_objLock.Unlock(); printf("unlock ret %d\n",iResult); printf("sleep %d sec\n",iSleep); Sleep(iSleep*1000); printf("lock and sleep %d sec\n",iSleep); g_objLock.Lock(); Sleep(iSleep*1000); printf("start 2\n"); CreateThread(NULL, 0, ThrdFun2, NULL, 0, NULL); Sleep(999*1000); system("pause"); return 0; }环境是vs2005,建工程的时候选择了预编译头,所以会有stdafx.h。
CMutex使用时的注意事项,以及CMutex::Unlock何时会返回0
原文地址:http://blog.csdn.net/louobaichu/article/details/44155507