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;
}