#include <windows.h>
#include <iostream.h>
DWORD WINAPI FunThread(LPVOID lpPra);
DWORD WINAPI FunThread2(LPVOID lpPra);
int iIndex = 0;
int tickets = 100;
HANDLE hMutex;//互斥对象句柄
void main()
{
HANDLE hThread1,hThread2;
hThread1 = CreateThread(NULL,0,FunThread,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,FunThread2,NULL,0,NULL);
CloseHandle(hThread1); //关闭线程句柄
CloseHandle(hThread2);
hMutex = CreateMutex(NULL,FALSE,NULL);
Sleep(4000);
}
DWORD static WINAPI FunThread(LPVOID lpPra)
{
WaitForSingleObject(hMutex,INFINITE);
while(true)
{
if(tickets > 0)
{
Sleep(1);
cout << "thread1 sells tickets : " << tickets-- << endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD static WINAPI FunThread2(LPVOID lpPra)
{
WaitForSingleObject(hMutex,INFINITE);
while(true)
{
if(tickets > 0)
{
Sleep(1);
cout << "thread2 sells tickets : " << tickets-- << endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
#include <iostream.h>
DWORD WINAPI FunThread(LPVOID lpPra);
DWORD WINAPI FunThread2(LPVOID lpPra);
int iIndex = 0;
int tickets = 100;
HANDLE hMutex;//互斥对象句柄
void main()
{
HANDLE hThread1,hThread2;
hThread1 = CreateThread(NULL,0,FunThread,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,FunThread2,NULL,0,NULL);
CloseHandle(hThread1); //关闭线程句柄
CloseHandle(hThread2);
hMutex = CreateMutex(NULL,FALSE,NULL);
Sleep(4000);
}
DWORD static WINAPI FunThread(LPVOID lpPra)
{
WaitForSingleObject(hMutex,INFINITE);
while(true)
{
if(tickets > 0)
{
Sleep(1);
cout << "thread1 sells tickets : " << tickets-- << endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD static WINAPI FunThread2(LPVOID lpPra)
{
WaitForSingleObject(hMutex,INFINITE);
while(true)
{
if(tickets > 0)
{
Sleep(1);
cout << "thread2 sells tickets : " << tickets-- << endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}