下面是个例子:
#include <Windows.h>
#include <iostream>
using std::cout;
using std::endl;
typedef struct _Mutex
{
LPTSTR lpStr;
HANDLE mutex;
_Mutex(LPTSTR s,HANDLE m){lpStr=s;mutex=m;}
}* _PMutex;
DWORD WINAPI f1(LPVOID lp)
{
for (int i=0;i<100;i++)
{
WaitForSingleObject(_PMutex(lp)->mutex,INFINITE);
cout<<_PMutex(lp)->lpStr<<i<<endl;
ReleaseMutex(_PMutex(lp)->mutex);
}
return 0;
}
DWORD WINAPI f2(LPVOID lp)
{
for (int i=0;i<100;i++)
{
WaitForSingleObject(_PMutex(lp)->mutex,INFINITE);
cout<<_PMutex(lp)->lpStr<<i<<endl;
ReleaseMutex(_PMutex(lp)->mutex);
}
return 0;
}
void main()
{
HANDLE hMutex=CreateMutex(NULL,FALSE,NULL);
HANDLE hThread1=CreateThread(NULL,0,f1,(LPVOID)new _Mutex(\"first: \",hMutex),0,NULL);
HANDLE hThread2=CreateThread(NULL,0,f1,(LPVOID)new _Mutex(\"second: \",hMutex),0,NULL);
Sleep(1000);
CloseHandle(hThread1);
CloseHandle(hThread1);
}