#include "stdafx.h"
#include <iostream>
using namespace Std;
#include "Windows.h"
int index = 0;
int tickets = 100;
HANDLE Hmutex = null;//Mutex
HANDLE hevent = null;//Event
Critical_section G_cs; Critical section
DWORD WINAPI Func1 (LPVOID pparam)
{
while (true)
{
WaitForSingleObject (Hmutex, INFINITE);
WaitForSingleObject (Hevent,infinite);
EnterCriticalSection (&g_cs);
if (tickets> 0)
{
Sleep (1);
cout<< "Thread1 Sell tickets:" <<tickets--<<endl;
}
Else
Break
ReleaseMutex (Hmutex);
SetEvent (hevent);
LeaveCriticalSection (&g_cs);
}
return 0;
}
DWORD WINAPI Func2 (LPVOID pparam)
{
while (true)
{
WaitForSingleObject (Hmutex,infinite);
WaitForSingleObject (Hevent,infinite);
EnterCriticalSection (&g_cs);
if (tickets> 0)
{
Sleep (1);
cout<< "Thread2 Sell tickets:" <<tickets--<<endl;
}
Else
Break
ReleaseMutex (Hmutex);
SetEvent (hevent);
LeaveCriticalSection (&g_cs);
}
return 0;
}
void Main ()
{
HANDLE hThread1 =createthread (null, 0, FUNC1, NULL, 0, NULL);
HANDLE hThread2 =createthread (null, 0, FUNC2, NULL, 0, NULL);
CloseHandle (HTHREAD1);
CloseHandle (HTHREAD2);
Hmutex = CreateMutex (null,false,null);
Hevent =createevent (NULL, FALSE, true,null);
InitializeCriticalSection (&g_cs);
Sleep (4000);
DeleteCriticalSection (&g_cs);
}
C + + interprocess communication (common understanding example)-Buy tickets