I'm trying to do the third writer/reader problem with semaphore (as mention on wiki). But it's not working properly. First 16-element array seem to work properly. But after first, it got wrong. Even though I think I'm almost there, I can't find the error at all. My code is as the following :
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#include <fcntl.h>
#define TRUE 1
#define MAX 16
#define STR_MAX 200
void *writer(void*);
void *reader(void*);
void freebuff(char*);
char *init(char* , int); void print_buff();
int readCount = 0;
sem_t mutex ,write, read;
char* CirBuf[MAX];
int main(int argc, char* argv[])
{
FILE *file1, *file2;
int i;
pthread_t read_thread[3], write_thread[3];
if( argc < 3)
{
printf("wrong format. Should be <program> <input_file> <output_file>\n");
exit(-1);
}
if((file1 = fopen(argv[1],"r")) == NULL)
{
printf("input %s file is not exist\n", argv[1]);
exit(-1);
}
if((file2 = fopen(argv[2],"w+")) == NULL)
{
printf("output %s file cannot be created\n", argv[2]);
fclose(file1);
exit(-1);
}
sem_init(&mutex, 0, 1);
sem_init(&write, 0, 1);
sem_init(&read, 0, 16);
for(i = 0; i <3; i++)
{
pthread_create(&write_thread[i], NULL, writer,(void *)file2);
pthread_create(&read_thread[i], NULL, reader,(void *)file1);
}
for(i = 0; i <3; i++)
{
pthread_join(write_thread[i], NULL);
pthread_join(read_thread[i], NULL);
}
sem_destroy(&mutex);
sem_destroy(&write);
sem_destroy(&read);
pthread_exit(NULL);
}
char *init(char* buffer, int size)
{
if((buffer = (char *)malloc(size))== NULL)
{
printf("error occurs while initialize");
exit(EXIT_FAILURE);
}
return buffer;
}
void freebuff(char *buffer)
{
buffer = NULL;
free(buffer);
}
void *reader(void *argv)
{
char buffer[STR_MAX];
int readNo, i=0, firstTime = 0;
sem_getvalue(&read, &readNo);
while(readNo > 0 && !feof(argv))
{
sem_wait(&read);
sem_wait(&mutex);
if(readNo > 15 || readNo < 1) readNo = 15;
fgets(buffer, sizeof(buffer), argv);
CirBuf[readNo - 1] = init(CirBuf[readNo - 1], strlen(buffer));
strcpy(CirBuf[readNo - 1], buffer);
readNo = readNo- 1;
printf("pass here\n");
sem_post(&mutex);
sem_post(&write);
}
if(readNo == 0) sem_post(&write);
pthread_exit(NULL);
}
void *writer(void *argv)
{
int i= 1, j = 0;
sem_getvalue(&write, &i);
while(i > 0)
{
sem_wait(&write);
sem_wait(&mutex);
sem_getvalue(&write, &i);
if(CirBuf[i] != NULL)
{
fputs(CirBuf[i], argv);
freebuff(CirBuf[i]);
}
sem_post(&mutex);
sem_post(&read);
}
pthread_exit(NULL);
}
It seem less than 16 element is correct. but if more than 15, it got error.
Can u please explain me what is not correct in this coding? Thanks in advance to you all.