Title: Create two threads simulator train station Two windows ticketing procedures, window ticketing time is 1 seconds, two windows can not be sold at the same time
#include <Windows.h>
#include <iostream>
using namespace Std;
This is a small program of 2 threads simulating buy train tickets
DWORD WINAPI Fun1proc (LPVOID lpparameter);//thread data
DWORD WINAPI Fun2proc (LPVOID lpparameter);//thread data
int index = 0;
int tickets = 10;
HANDLE Hmutex;
int main ()
{
HANDLE HThread1;
HANDLE hThread2;
Creating Threads
HThread1 = CreateThread (null, 0, fun1proc, NULL, 0, NULL);
HThread2 = CreateThread (null, 0, fun2proc, NULL, 0, NULL);
CloseHandle (HTHREAD1);
CloseHandle (HTHREAD2);
Creating a Mutex Object
Hmutex = CreateMutex (NULL, TRUE, "tickets");
if (Hmutex)
{
if (ERROR already EXISTS = = GetLastError ())
{
cout << "Only one instance can run!" << Endl;
return 0;
}
}
WaitForSingleObject (Hmutex, INFINITE);
ReleaseMutex (Hmutex);
ReleaseMutex (Hmutex);
Sleep (4000);
return 0;
}
Entry function for thread 1
DWORD WINAPI Fun1proc (LPVOID lpparameter)
{
while (true)
{
ReleaseMutex (Hmutex);
WaitForSingleObject (Hmutex, INFINITE);
if (Tickets > 0)
{
Sleep (1);
cout << "Thread1 Sell ticket:" << tickets--<< Endl;
}
Else
Break
ReleaseMutex (Hmutex);
}
return 0;
}
Entry function for thread 2
DWORD WINAPI Fun2proc (LPVOID lpparameter)
{
while (true)
{
ReleaseMutex (Hmutex);
WaitForSingleObject (Hmutex, INFINITE);
if (Tickets > 0)
{
Sleep (1);
cout << "Thread2 Sell ticket:" << tickets--<< Endl;
}
Else
Break
ReleaseMutex (Hmutex);
}
return 0;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Create two threads simulate train station two windows ticketing procedure