title: Sleeping barber using semaphore
body: <p>I am having a problem in the synchronisation of threads. I m trying to implement sleeping barber problem in a different approach.
  When i run the code the threads run in a completely vague manner.
  When i add join to the threads the processes run one by one which is not required.
  I know the solutions to the sleeping barber problem but can anybody tell me what is the problem with this code.?</p>
  
  <p>Thank You</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;pthread.h&gt;
  #include&lt;time.h&gt;
  #include &lt;unistd.h&gt;
  #include&lt;semaphore.h&gt;
  #define n 1
  #define n1 50
  int status[n];
  int b=0;
  sem_t mutex;
  sem_t barber;
  void *barb()
  {
  printf("Barber Sleeping\n");
  b=1;
  sem_wait(&amp;barber);
  printf("Barber woke up\n");
  sleep(1);
  b=0;
  }
  void *handler(void *ptr)
  {
  int x; 
      x = *((int *) ptr);
  int flag=0;
  int i=0;
  int cnt=0;
  for(i=0;i&lt;n;i++)
  {
      if(status[i]==1)
      {
      flag=1;
      cnt++;      
      }
  }
  printf("Count=%d",cnt);
  if(cnt==n)
  {
      printf("%d Customer Returned\n",x);
      return 0;
  }
  if(flag==1)
  {
      status[x]=1;
      printf("%d Customer waiting\n",x); 
      sem_wait(&amp;mutex);
  }
  if(b==1)
  {
      printf("Customer %d woke up barber",x);
      sem_post(&amp;barber);
  }   
  printf("Cutting Hair of customer %d\n",x);
  status[x]=1;
  sleep(5);
  flag=0;
  for(i=0;i&lt;n;i++)
  {
      if(status[i]==1)
      {
          flag=1;     
      }
  }
  status[x]=0;
  printf("Finished cutting Hair of customer %d\n",x);
  if(flag==1) 
  sem_post(&amp;mutex);
  }
  int main()
  {
  sem_init(&amp;mutex, 0, n);
  sem_init(&amp;barber, 0, 1);
  pthread_t thread[n1];
  pthread_t barber;
  int i=0;
  for(i=0;i&lt;n;i++)
  {
      status[i]=0;
  }
  
  pthread_create(&amp;barber,NULL,barb,NULL);
  pthread_join(barber,NULL);
  for(i=0;i&lt;n1;i++)
  {
      sleep(1);
      printf("Customer entered %d\n",i);
      pthread_create(&amp;thread[i], NULL, handler, (void *)&amp;i);
      //pthread_join(thread[i],NULL);
  }
  for(i=0;i&lt;n1;i++)
  {
      //pthread_join(thread[i],NULL);
  }
  //sem_post(&amp;barber);
  </code></pre>
  
  <p>}</p>