20101112.cpp: Defines the entry point for the console application.
Using semaphores to achieve thread synchronization
#include "stdafx.h"
#include "Windows.h"
#include "iostream"
using namespace Std;
int num=1;
HANDLE Hdemaphore;
unsigned long _stdcall ThreadProc1 (void *lpparameter)
{
while (num<100)
{
Long Count;
WaitForSingleObject (Hdemaphore,infinite);
cout<< "Semaphore 1 Current Count" <<num<<endl;
num++;
Sleep (100);
ReleaseSemaphore (Hdemaphore,1,&count);
}
return 0;
}
unsigned long _stdcall ThreadProc2 (void *lpparameter)
{
while (num<100)
{
Long Count;
WaitForSingleObject (Hdemaphore,infinite);
cout<< "Semaphore 2 Current Count" <<num<<endl;
num++;
Sleep (100);
ReleaseSemaphore (Hdemaphore,1,&count);
}
return 0;
}
int _tmain (int argc, _tchar* argv[])
{
HANDLE Hthread1=createthread (null,0,threadproc1,null,0,null);
HANDLE Hthread2=createthread (null,0,threadproc2,null,0,null);
Hdemaphore=createsemaphore (null,1,100,_t ("Sem"));
CloseHandle (HTHREAD1);
CloseHandle (HTHREAD2);
while (true)
{
;
}
return 0;
}