Create two threads simulate train station two windows ticketing procedure

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.