I am working on writting 2 programs, the first was using the algorithm provided to me which basically blocks the writter out as long as there are readers. That wasn't much of a problem. I then wanted to change it to allow the writter to gain access without changing the delay of the current algorithm so I creating a semaphore q basically like a que to allow the writter in and it seems to work however I'm a little confused on what I did and was hoping someone could help me- I believe I created q to allow the writter in after all readers are done reading but every now and then it will let the writter in while there is still a reader and I thought by gaining exclusive access it shouldn't. Anyways if you don't mind taking a look at my code and any suggestions would be helpful. keep in mind the only thing I added from my original was sem q
Code:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#define MAXTHREAD 4 /* define # readers */
void access_database(); /* prototypes */
void non_access_database();
void* reader(void*);
void* writer(void*);
sem_t mutex; /* controls access to rc */
sem_t db; /* controls access to db */
sem_t q; /* establish que */
int rc = 0; /* number of processes reading or wanting to */
int main()
{
pthread_t readers[MAXTHREAD],writerTh;
int index;
int ids[MAXTHREAD]; e readers and initialize mutex, q and db-set them to 1 */
sem_init(&mutex,0,1);
sem_init(&db,0,1);
sem_init (&q,0,1);
for(index = 0; index < MAXTHREAD; index ++)
{
ids[index]=index+1; /* create readers and error check */
if(pthread_create(&readers[index],0,reader,&ids[index])!=0){
perror("Cannot create reader!");
exit(1);
}
}
if(pthread_create(&writerTh,0,writer,0)!=0){
perror("Cannot create writer"); /* create writers and error check */
exit(1);
}
pthread_join(writerTh,0);
sem_destroy(&mutex);
sem_destroy(&db);
sem_destroy (&q);
return 0;
}
void* reader(void*arg) /* readers function to read */
{
int index = *(int*)arg;
while(1){
sem_wait(&q);
sem_wait(&mutex);
rc++;
if(rc == 1) sem_wait(&db);
sem_post(&mutex);
access_database();
sem_post (&q);
printf("Thread %d reading\n",index);
sleep(index);
sem_wait(&mutex);
rc--;
if(rc == 0) sem_post(&db);
sem_post(&mutex);
non_access_database();
}
return 0;
}
;
void* writer(void*arg) /* writer's function to write */
{
while(1){
non_access_database();
sem_wait (&q);
sem_wait(&db);
access_database();
sem_post (&q);
printf("Writer is now writing...Number of readers: %d\n",rc);
sleep(1);
sem_post(&db);
}
return 0;
}
void access_database()
{
}
void non_access_database()
{