Examples of mutex objects in multiple threads

Source: Internet
Author: User
Z from Sun Xin's books

# Include <windows. h>
# Include <iostream>

DWORD winapi pthread (lpvoid lpparameter); // thread 1
DWORD winapi sthread (lpvoid lpparameter); // thread 2
Using namespace STD;
Int tickets = 100;
Handle hmutex; // mutex object handle
Void main ()
{
Handle hthread1;
Handle hthread2;

Cout <"Start Cell:" <Endl;
Hthread1 = createthread (null, 0, pthread, null, 0, null );
Sleep (10 );
Hthread2 = createthread (null, 0, sthread, null, 0, null );


Closehandle (hthread2 );
Closehandle (hthread1 );

// Create a mutex object
Hmutex = createmutex (null, false, null );

Getchar ();
// Sleep (1, 5000 );
}

// Thread1
DWORD winapi pthread (lpvoid lpparameter)
{
While (true)
{
Waitforsingleobject (hmutex, infinite );
If (tickets> 0)
{
Sleep (1000 );
Cout <"PPP cell Ticket:" <tickets -- <Endl;
}
Else
Break;
Releasemutex (hmutex );

}
Return 0;
}

// Thread2
DWORD winapi sthread (lpvoid lpparameter)
{
While (true)
{
Waitforsingleobject (hmutex, infinite );
If (tickets> 0)
{
Sleep (1000 );
Cout <"Sss cell Ticket:" <tickets -- <Endl;
}
Else
Break;
Releasemutex (hmutex );

}
Return 0;
}

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.