Train station Ticketing System Simulation Program

Source: Internet
Author: User

Tag: Object thread

# Include <windows. h>
# Include <iostream. h>
DWORD winapi fun1proc (lpvoid lparameter );
DWORD winapi fun2proc (lpvoid lparameter );
Int Index = 0;
Int tickets = 100;
Handle hmutex; // defines the mutex object handle.

Int main ()
{
Handle HT1; // thread-1 handle
Handle ht2; // thread 2 handle
HT1 = createthread (null, 0, fun1proc, null, 0, null); // create thread 1, (null (default security), initial house size, entry function, PASS Parameters, 0 (the creation thread runs immediately), the ID of the receiving thread)
Ht2 = createthread (null, 0, fun2proc, null, 0, null); // create thread 2
Closehandle (HT1 );
Closehandle (ht2 );
Hmutex = createmutex (null, false, null); // creates a mutex object (null (default security), the owner of the mutex object, and the name of the mutex object (null is anonymous ))
Sleep (4000); // wait
Return 0;
}
DWORD winapi fun1proc (lpvoid lparameter) // thread 1
{
While (1)
{
Waitforsingleobject (hmutex, infinite); (handle of the mutex object, Waiting Time)
If (tickets> 0)
{
Sleep (1 );
Cout <"One ticket sold by a thread:" <tickets -- <Endl;
}
Else
{
Break;
}
Releasemutex (hmutex); // release a mutex object
}
Return 0;
}
DWORD winapi fun2proc (lpvoid lparameter) // thread 2
{
While (1)
{
Waitforsingleobject (hmutex, infinite );
If (tickets> 0)
{
Sleep (1 );
Cout <"One ticket sold by thread 2:" <tickets -- <Endl;
}
Else
{
Break;
}
Releasemutex (hmutex );
}
Return 0;
}

Train station Ticketing System Simulation Program

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.