Professional Documents
Culture Documents
#Include #Include Using Namespace STD Handle Hthreada, Hthreadb Handle Hsemaphore
#Include #Include Using Namespace STD Handle Hthreada, Hthreadb Handle Hsemaphore
#Include #Include Using Namespace STD Handle Hthreada, Hthreadb Handle Hsemaphore
#include <Windows.h>
using namespace std;
HANDLE hthreadA, hthreadB;
HANDLE hsemaphore;
//semaphore counting k liye use hta hai.. jysy k
hmain aik particular amount of threads chahiyen k
itni threads hi enter hon mtlb hm ny limit lgani hai
tou hm semaphore sy protect kraingy usy.. jitni
threads allow krni hain hmain us number sy
semaphore ko initialize krwa daingy
DWORD threadid, threadid2;
//a dword is an unsigned, 32-bit unit of data. It can
contain an integer value in the range 0 through
4,294,967,295.
int a,b, c;
//LPVOID is simply a Windows API typedef for void*
pointer--
DWORD WINAPI MyFunA(LPVOID lpParam)
//WINAPI is a macro that expands to __stdcall
which means that the callee cleans the stack.
{
cout<<"Enter value of a ";
cin>>a;
cout<<"Enter value of b ";
endl --> next line
cin ---> input
cout ---> output/print
cin>>b;
cout<<endl;
ReleaseSemaphore(hsemaphore, 1, 0);
When a thread completes the task, it uses the
ReleaseSemaphore function to increment the
semaphore's count, thus enabling another waiting
thread to perform the task.
}
DWORD WINAPI MyFunB(LPVOID lpParam)
{
WaitForSingleObject(hsemaphore, 'INFINITE');
//Before a thread attempts to perform the task, it uses
the WaitForSingleObject function to determine whether
the semaphore's current count permits it to do so. The
wait function's time-out parameter is set to zero, so the
function returns immediately if the semaphore is in the
nonsignaled state. WaitForSingleObject decrements the
semaphore's count by one.
c=a+b;
cout<<"sum of a and b is "<<c<<endl;
}
int main()
{
hthreadA = CreateThread(NULL, 0, MyFunA,
NULL, 0, &threadid);
hthreadB = CreateThread(NULL, 0, MyFunB,
NULL, 0, &threadid2);
hsemaphore = CreateSemaphoreW(NULL, 0, 1,
NULL);