# mutex73
# imsaws@126.com
# Now in Xidian University
精简了一下网上的程序
//Lock.h
#pragma once
#include <windows.h>
class Mutex
{
public:
Mutex() { m_mutex = ::CreateMutex(NULL, FALSE, NULL); }
~Mutex() { ::CloseHandle(m_mutex); }
virtual void Lock() const { DWORD d = WaitForSingleObject(m_mutex, INFINITE); }
virtual void Unlock() const { ::ReleaseMutex(m_mutex); }
private:
HANDLE m_mutex;
};
//main.cpp
#include <iostream>
#include <process.h>
#include "Lock.h"
using namespace std;
Mutex g_Lock;
unsigned int __stdcall StartThread(void *pParam)
{
char *pMsg = (char *)pParam;
if (!pMsg)
{
return (unsigned int)1;
}
g_Lock.Lock();
for( int i = 0; i < 5; i++ )
{
cout << pMsg << endl;
Sleep( 500 );
}
g_Lock.Unlock();
return (unsigned int)0;
}
int main(int argc, char* argv[])
{
HANDLE hThread1, hThread2;
unsigned int uiThreadId1, uiThreadId2;
char *pMsg1 = "First print thread.";
char *pMsg2 = "Second print thread.";
hThread1 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)pMsg1, 0, &uiThreadId1);
hThread2 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)pMsg2, 0, &uiThreadId2);
DWORD dwRet = WaitForSingleObject(hThread1,INFINITE);
if ( dwRet == WAIT_TIMEOUT )
{
TerminateThread(hThread1,0);
}
dwRet = WaitForSingleObject(hThread2,INFINITE);
if ( dwRet == WAIT_TIMEOUT )
{
TerminateThread(hThread2,0);
}
::CloseHandle(hThread1);
::CloseHandle(hThread2);
system("pause");
return 0;
}
结果:
First print thread.
First print thread.
First print thread.
First print thread.
First print thread.
Second print thread.
Second print thread.
Second print thread.
Second print thread.
Second print thread.
请按任意键继续. . .
备忘:
每个信号获取mutex之后都会WaitForSingleObject,这是在等在前一个获取资源线程的unlock,当ReleaseMutex发生时,WaitForSingleObject就会return使下一个线程获取资源
原文地址:http://blog.csdn.net/u014539401/article/details/45023237