sem_t w,r,s1,s2,s3;
pthread_mutex_t m;


int main(int argc, char* argv[])
{
  
   mutex and semaphores initialization .....

   call threads....

   wait until finish and cancel threads...
   
   clean threads and semaphores

   [I]exit;[/I]
}



void *reader(void *argv)
{
   
   while(TRUE)
   {
      sem_wait(&r);
      sem_wait(&s1);
      pthread_mutex_lock(&m);
      
      ... read data.....

      pthread_mutex_unlock(&m);
      sem_post(&s1);
      sem_post(&w);   
   } 
   printf("Done read\n");
   sem_post(&extra2);
   pthread_exit(NULL);
}

void *writer(void *argv)
{
   
   while(TRUE)
   {
     sem_wait(&w);
     sem_wait(&s1);
     pthread_mutex_lock(&m);
     
    
     pthread_mutex_unlock(&m);
     sem_post(&s1);
     sem_post(&r);
   }
   printf("Done Write\n");
   sem_post(&s3);
   pthread_exit(NULL);
}

I wrote a reader/writer issue and now it's writing the same as from the source ... but sometime it become unstable and making output wrong or stop working.. Can someone plz show me the unstable part? if need, i'll also provide my code. Thanks in advance..

Post the code or just a part of code. Which compiler are you using? Try to compile it step by step for 5-8 times and you will get to know, which part is guilty :-)

sem_t w,r,s1,s2,s3;
pthread_mutex_t m;


int main(int argc, char* argv[])
{
  
   mutex and semaphores initialization .....

   call threads....

   wait until finish and cancel threads...
   
   clean threads and semaphores

   [I]exit;[/I]
}



void *reader(void *argv)
{
   
   while(TRUE)
   {
      sem_wait(&r);
      sem_wait(&s1);
      pthread_mutex_lock(&m);
      
      ... read data.....

      pthread_mutex_unlock(&m);
      sem_post(&s1);
      sem_post(&w);   
   } 
   printf("Done read\n");
   sem_post(&extra2);
   pthread_exit(NULL);
}

void *writer(void *argv)
{
   
   while(TRUE)
   {
     sem_wait(&w);
     sem_wait(&s1);
     pthread_mutex_lock(&m);
     
    
     pthread_mutex_unlock(&m);
     sem_post(&s1);
     sem_post(&r);
   }
   printf("Done Write\n");
   sem_post(&s3);
   pthread_exit(NULL);
}

I wrote a reader/writer issue and now it's writing the same as from the source ... but sometime it become unstable and making output wrong or stop working.. Can someone plz show me the unstable part? if need, i'll also provide my code. Thanks in advance..

This article has been dead for over six months. Start a new discussion instead.