1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
|
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int in=0;
int out=0;
int shared_counter=0;
char* buffer[10];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // mutual exclusion lock
void putonbuf()
{
char file[10]={0};
int i=0;
char str[30]={0};
int j=0;
FILE *fptr;
gets(file);
fptr = fopen(file,"r");
while(1)
{
while(shared_counter==10);
str[i]=fgetc(fptr);
if(str[i]==EOF)
break;
if(str[i]=='\n')
{
pthread_mutex_lock(&mutex);
printf("putting\n");
str[i]='\0';
buffer[j]=malloc(strlen(str)+1);
strcpy(buffer[j],str);
j++;
i=-1;
char str[30]={0};
shared_counter++;
pthread_mutex_unlock(&mutex);
}
i++;
}
fclose(fptr);
}
void getoffbuf(){
char* data;
int a=0;
pthread_mutex_lock(&mutex);
printf("consumer is removing\n");
data=buffer[out];
data=(char*)StrReverse(data);
puts(data);
out=(out+1)%10;
shared_counter--;
pthread_mutex_unlock(&mutex); // unlock queue
}
void* producer()
{
putonbuf();
}
void* consumer()
{
while(1)
{
while (shared_counter == 0);
getoffbuf();
}
}
char* StrReverse(char* str)
{
char *temp, *ptr;
int len, i;
temp=str;
for(len=0; *temp !='\0';temp++, len++);
ptr=malloc(sizeof(char)*(len+1));
for(i=len-1; i>=0; i--)
ptr[len-i-1]=str[i];
ptr[len]='\0';
return ptr;
}
int main()
{
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,producer,NULL)){
fprintf(stderr, "thread creation failed.");
exit(1);
}
if(pthread_create(&tid2,NULL,consumer,NULL)){
fprintf(stderr, "thread creation failed.");
exit(1);
}
pthread_join(tid1, NULL);
pthread_cancel(tid2);
return 0;
}
|