title: Reader Writer program in C using mutexes and pthreads
body: <p>I am stuck on a Reader/Writer problem in C. Can anybody explain me what is happening in the code below.  I dont understand how the execution flows after the pthread_create(&amp;tid,NULL,writer,NULL) line.</p>
  
  <pre><code>#include&lt;pthread.h&gt;
  //#include&lt;semaphore.h&gt;
  #include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  
  pthread_mutex_t x,wsem;
  pthread_t tid;
  int readcount;
  
  void intialize()
  {
      pthread_mutex_init(&amp;x,NULL);
      pthread_mutex_init(&amp;wsem,NULL);
      readcount=0;
  }
  
  void * reader (void * param)
  {
      int waittime;
      waittime = rand() % 5;
      printf("\nReader is trying to enter");
      pthread_mutex_lock(&amp;x);
      readcount++;
      if(readcount==1)
          pthread_mutex_lock(&amp;wsem);
      printf("\n%d Reader is inside ",readcount);
      pthread_mutex_unlock(&amp;x);
      sleep(waittime);
      pthread_mutex_lock(&amp;x);
      readcount--;
      if(readcount==0)
          pthread_mutex_unlock(&amp;wsem);
      pthread_mutex_unlock(&amp;x);
      printf("\nReader is Leaving");
  }   
  
  void * writer (void * param)
  {
      int waittime;
      waittime=rand() % 3;
      printf("\nWriter is trying to enter");
      pthread_mutex_lock(&amp;wsem);
      printf("\nWrite has entered");
      sleep(waittime);
      pthread_mutex_unlock(&amp;wsem);    
      printf("\nWriter is leaving");
      sleep(30);
      exit(0);
  }
  
  int main()
  {
      int n1,n2,i;    
      printf("\nEnter the no of readers: ");
      scanf("%d",&amp;n1);
      printf("\nEnter the no of writers: ");
      scanf("%d",&amp;n2);
      for(i=0;i&lt;n1;i++)
          pthread_create(&amp;tid,NULL,reader,NULL);  
      for(i=0;i&lt;n2;i++)
          pthread_create(&amp;tid,NULL,writer,NULL);
      sleep(30);
      exit(0);
  }
  </code></pre>