// MultiThread. cpp: defines the entry point of the console application.
//
# Include "stbdafx. h"
# Include <windows. h>
# Include <iostream>
Using namespace std;
Int tickets = 100;
HANDLE hMutex;
Dword winapi Fun1Proc (LPVOID lp );
Dword winapi Fun2Proc (LPVOID lp );
Int _ tmain (int argc, _ TCHAR * argv [])
{
HANDLE hThread1, hThread2;
HThread1 = CreateThread (NULL, 0, Fun1Proc, NULL, 0, NULL );
HThread2 = CreateThread (NULL, 0, Fun2Proc, NULL, 0, NULL );
CloseHandle (hThread1 );
CloseHandle (hThread2 );
HMutex = CreateMutex (NULL, FALSE, NULL );
Sleep (2000 );
System ("pause ");
Return 0;
}
Dword winapi Fun1Proc (LPVOID lp)
{
While (1)
{
WaitForSingleObject (hMutex, INFINITE );
If (tickets> 0)
{
Sleep (10 );
Cout <"thread1 extends ticket." <tickets -- <endl;
}
Else
Break;
ReleaseMutex (hMutex );
}
Return 0;
}
Dword winapi Fun2Proc (LPVOID lp)
{
While (1)
{
WaitForSingleObject (hMutex, INFINITE );
If (tickets> 0)
Cout <"thread2 extends ticket." <tickets -- <endl;
Else
Break;
ReleaseMutex (hMutex );
}
Return 0;
}
Author: tbw