semaphore.c
//***********************************************************************
//
// Name: semaphore.c
//
// Author: Poonam Hajgude
//
// Description: Main program creates three semaphores and two threads
// to solve producer & Consumer problem.
//
// Created: March 21st, 2004.
//
//***********************************************************************
#include <windows.h>
#include <stdio.h>
#include<conio.h>
const INT numBufSegs=10;
char pData, cData;
char Buffer[10];
char alphaBet[]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
INT pindeX=0,cindeX=0,i=0,oktr=0;
HANDLE pHandle,cHandle,full,empty,mutex;
DWORD threadID;
void Producer()
{
printf("Producer thread startting
");
while(1)
{
//Produce Data
pData=alphaBet[i++];
WaitForSingleObject(empty,INFINITE);
WaitForSingleObject(mutex,INFINITE);
//add data to buffer
Buffer[pindeX++]=pData;
pindeX = pindeX % numBufSegs;
ReleaseSemaphore(mutex,1,0);
ReleaseSemaphore(full,1,0);
}
printf("Producer thread existing
");
}
void Consumer()
{
printf("Consumer thread startting
");
printf("Data are
");
for(oktr=0;oktr<26;oktr++)
{
WaitForSingleObject(full,INFINITE);
WaitForSingleObject(mutex,INFINITE);
//move data from buffer
cData=Buffer[cindeX++];
cindeX=cindeX % numBufSegs;
ReleaseSemaphore(mutex,1,0);
ReleaseSemaphore(empty,1,0);
printf("%c ",cData);
}
printf("
Consumer thread existing
");
TerminateThread(pHandle,1);
}
int main(void)
{
full=CreateSemaphore(0,0,numBufSegs,0);
if(full==0)
printf("Can not create full Semaphore
");
empty=CreateSemaphore(0,numBufSegs,numBufSegs,0);
if(empty==0)
printf("Can not create empty Semaphore
");
mutex=CreateSemaphore(0,1,1,0);
if(full==0)
printf("Can not create mutex Semaphore
");
//Create threads
pHandle=CreateThread(0,0,(LPTHREAD_START_ROUTINE) Producer,0,0,&threadID);
if(pHandle==0)
printf("Can not create thread for Producer
");
cHandle=CreateThread(0,0,(LPTHREAD_START_ROUTINE) Consumer,0,0,&threadID);
if(cHandle==0)
printf("Can not create thread for Consumer
");
//Wait for Consumer thread to finish first
WaitForSingleObject(cHandle,INFINITE);
printf("Consumer thread termination
");
//Wait for Producer thread to finish
WaitForSingleObject(pHandle,INFINITE);
printf("Producer thread termination
");
CloseHandle(full);
CloseHandle(empty);
CloseHandle(mutex);
CloseHandle(pHandle);
CloseHandle(cHandle);
exit(1);
}