Sunday, February 6, 2011

Process Synchronization


idealstudent.blogger.com

OBJECTIVE: IMPLEMENTATION OF PROCESS SYNCHRONIZATION
THEORY : Two condition variable control acess to the buffer condition variable is used to tell if the buffer is full,and the other is used to tell if the buffer is empty.when the producer wants to add an item to the buffer ,it checks to see if the buffer is full;if it is fullthe producer blocks on the cond_wait()call,waiting for an item to be removed from the buffer .when consumer remove the item from the buffer ,the buffer is no longer full ,so the producer is awakend from the cond_wait ()call.The producer is then allowed to add another item to the buffer .
PROGRAM :
#define_RehEENTRANT
#Iinclude,stdio.h>
#include<thead.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/uio>
#define BUFSIZE 512
#define BUFCNT 4
Struct {
Char buffer[BUFCNT][BUFSIZE];
Int byteinbuf[BUFCNT];

Mutex_t buflock;
Mutex_t donelock;
Cond_t addata;
Cond_remdata;
Int nextadd,nextrem,occ,done;
}buf;
Void *consumer(viod*);
Main(int argc,char **argv)
{
Int ifd,ofd;
Thread_t cons_thr;
If(argca!=3)
  Printf(“usage :%s<infile><outfile>\n”,argv[0]),exit(0);
if((ifd=open([argv[1],O_RDONLY))==-1);
{
fprintf("stderr,"can't  open file  %s\n",argv[1]);
exit(1);
}
if((ofd=open(argv[2],O_WRONLY|O_CREAT,0666))===-1)
{
fprintf("stderr ,"can't open file %s\n",argv[2]);
exit(1);
}
Buf.nextadd=Buf.nextrem=buf.occ=Buf.done=0;
thr_setconcurrency(2);
thr_create(NULL,0,consumer,(void *)ofd,NULL,&cons_thr);
while(1){
mutex_lock(&Buf.buflock);
while(Buf.occ==BUFCNT)
cond_wait(&Buf.remdata,&Buf,buflock);
if(Buf.byteinbuf[Buf.nextadd]==0) {
mutex_lock(&Buf.donellock);
Buf.done=1;
mutex_unlock(&Buf.donelock);
cond_signal(&Buf.adddata);
mutex_unlock(&Buf.buflock);
break;
}
Buf.nextadd=++Buf.nextadd%BUFCNT;
Buf.occ++;
cond_signal(&Buf.adddata);
mutex_unlock(&Buf.buflock);
}
close(ifd);
thr_join(cons_thr,0,NULL);
return(0);
}
void *consumer(void *arg)
{
int fd=(int)arg;
while(1) {
mutex_lock(&Buf.buflock);
break;
}
while(Buf.occ==0&&!Buf.done)
 cond_wait(&Buf.adddata,&Buf.buflock);
write(fd,Buf.buffer[Buf.nextrem],Buf.byteinbuf[Buf.nextrem]);
Buf.nextrem=++Buf.nextrem%BUFCNT;
Buf.occ--;
cond_signal(&Buf.remdata);
mutex_unlock(&Buf.buflock);
}
thr_exit((void *)0);
}












No comments:

Post a Comment