WaitForSingleObject其中有一个返回值WAIT_ABANDONED,在MSDN上的解释如下
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.
ABANDONED是抛弃,放弃的意思,MSDN的解释差不多就是:指定的object是互斥,但是却没有被拥有它的线程释放,在这个线程结束前。只有这个线程能获得这个互斥,互斥被置为无信号状态。
举个例子说明
UINT threada(LPVOID lpNum)
{
int iNum = (int)lpNum;
HANDLE hMutext = OpenMutex(MUTEX_ALL_ACCESS, NULL, "SS");
for(int i = 0; i < 8; i++)
{
printf("thread %d is waitforsingleobject\n", iNum);
DWORD dwRtn = WaitForSingleObject(hMutext, INFINITE);
int icopy = iCount;
Sleep(100);
iCount = icopy + 1;
printf("thread %d is %d\n", iNum, iCount);
// ReleaseMutex(hMutext);
}
CloseHandle(hMutext);
return 0;
}
UINT threadb(LPVOID lpNum)
{
int iNum = (int)lpNum;
HANDLE hMutext = OpenMutex(MUTEX_ALL_ACCESS, NULL, "SS");
for(int i = 0; i < 8; i++)
{
printf("thread %d is waitforsingleobject\n", iNum);
DWORD dwRtn = WaitForSingleObject(hMutext, INFINITE);
int icopy = iCount;
Sleep(100);
iCount = icopy + 1;
printf("thread %d is %d\n", iNum, iCount);
ReleaseMutex(hMutext);
}
CloseHandle(hMutext);
return 0;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CString strHello;
strHello.LoadString(IDS_HELLO);
cout << (LPCTSTR)strHello << endl;
}
HANDLE hMutext = CreateMutex(NULL, FALSE, "SS");
HANDLE pThread[3];
CWinThread *p1 = AfxBeginThread(AFX_THREADPROC(threada), (LPVOID)1);
CWinThread *p2 = AfxBeginThread(AFX_THREADPROC(threadb), (LPVOID)2);
CWinThread *p3 = AfxBeginThread(AFX_THREADPROC(threadb), (LPVOID)3);
pThread[0] = p1->m_hThread;
pThread[1] = p2->m_hThread;
pThread[2] = p3->m_hThread;
WaitForMultipleObjects(3, pThread, TRUE, INFINITE);
CloseHandle(hMutext);
return nRetCode;
}
在threada这个线程中,将ReleaseMutex(hMutext)这个函数注释掉,也就是threada获得hMutext互斥量,但是并不释放,这样hMutext就被abandon了,并且处于无信号状态
这个进程的结果,在vc中新建个工程跑一下,就可以更加形象的理解