多线程MultiThread.cpp
// MultiThread.cpp : 界说节制台应用措施的进口点。
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
int tickets = 100;
HANDLE hMutex;
DWORD WINAPI Fun1Proc(LPVOID lp);
DWORD WINAPI Fun2Proc(LPVOID lp);
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1,hThread2;
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex = CreateMutex(NULL,FALSE,NULL);
Sleep(2000);
system("pause");
return 0;
}
DWORD WINAPI Fun1Proc(LPVOID lp)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets > 0)
{
Sleep(10);
cout << "thread1 sell ticket." << tickets-- <<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lp)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets > 0)
cout << "thread2 sell ticket." << tickets-- <<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}