title: Looping threads accessing pthread mutex
body: <p>im building this application in which i have a client represented by a thread, running in loop (until it receives the instruction to terminate) trying to access a critical section of data in the server.</p>
  
  <p>When the first client connects to the server, he owns the lock to that mutex. all the subsequent connections are put to a hold. This is the "normal" part of it.</p>
  
  <p>But then, when the first thread unlocks, the loop brings it back to the begining and it should be contending for the lock again. But it's assumed that he still holds the lock and executes the critical section in an almost infinite loop (not infinite because we can terminate the thread, giving the lock away for the other threads). </p>
  
  <p>To resume it all...when the first client connects, it owns the lock forever. The other threads remain in a waiting line until the first thread terminates. Here's some code:</p>
  
  <p>The Server:</p>
  
  <pre><code>int main(int argc, char * argv[])
  {
      int servSock;     
      unsigned short servPort;  
      unsigned int clntLen;
  
      rcvBuf = (char *)malloc((MAXLINE)*sizeof(char));
      pthreads = (fifo_t*)malloc(sizeof(fifo_t));
  
      struct sockaddr_in servAddr; 
      struct sockaddr_in clntAddr; 
  
      pthread_attr_t custom_sched_attr;   
  
      int fifo_max_prio, fifo_min_prio, fifo_mid_prio;   
      struct sched_param fifo_param;    
  
      pthread_attr_init(&amp;custom_sched_attr);   
      pthread_attr_setinheritsched(&amp;custom_sched_attr, PTHREAD_EXPLICIT_SCHED);   
      pthread_attr_setschedpolicy(&amp;custom_sched_attr, SCHED_FIFO);
  
      fifo_max_prio = sched_get_priority_max(SCHED_FIFO);   
      fifo_min_prio = sched_get_priority_min(SCHED_FIFO);   
      fifo_mid_prio = (fifo_min_prio + fifo_max_prio)/2;   
  
      fifo_param.sched_priority = fifo_mid_prio;  
  
      pthread_attr_setschedparam(&amp;custom_sched_attr, &amp;fifo_param);
  
      if(argc !=2 ){
          fprintf(stderr,"Usage: %s &lt;Server Port&gt;\n",argv[0]);
          exit(1);
      }
  
      fifo_init(pthreads);
  
      db  = db_open("DB", O_RDWR, 0666);
      servPort = atoi(argv[1]);
  
      if((servSock = socket(AF_INET,SOCK_STREAM,0)) &lt; 0){ 
          perror("Error with Socket()");
          exit(1);
      }
  
      memset(&amp;servAddr,0,sizeof(servAddr));
      servAddr.sin_family = AF_INET;
      servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
      servAddr.sin_port = htons(servPort);
  
      if(bind(servSock,(struct sockaddr*)&amp;servAddr,sizeof(servAddr)) &lt; 0){
          perror("Error with bind()");
          exit(1);
      }
  
      if(listen(servSock,NUM_THREADS) &lt; 0){
          perror("Error with listen()");
          exit(1);
      }
  
      for(;;)
      { 
          printf("A estabelecer ligaçao!\n");
          clntLen = sizeof(clntAddr);
  
          if((clntSock = accept(servSock,(struct sockaddr*)&amp;clntAddr,&amp;clntLen)) &lt; 0)
          {
              perror("Error with accept()");
              exit(0);
          }
  
          printf("Ligação estabelecida!\n");
  
          pthread_create(&amp;thread,&amp;custom_sched_attr,&amp;HandleTcpClient,(void *)clntSock);
  
          printf("Continua a execução nesta thread: %d\n",(int)pthread_self());
     }
  
     exit(0);
  }
  
  void * HandleTcpClient(void * data){
  
     insert(pthreads,(int)pthread_self());
  
     int sock = (int)data;
  
     char * key = (char *)malloc(FIELD * sizeof(char));
     char * dados = (char *)malloc(FIELD * sizeof(char));
     char * vendDev = (char *)malloc(FIELD * sizeof(char));
     char * str = (char*)malloc(MAXLINE * sizeof(char));
  
     memset(key,0,sizeof(key));
     memset(dados,0,sizeof(dados));
     memset(vendDev,0,sizeof(vendDev));
     memset(str,0,sizeof(str));
  
     while(1)
     {
     start:
  
         printf("Sem Lock: %d com socket: %d\n",(int)pthread_self(),sock);
  
         pthread_mutex_lock(&amp;mutexdb);
  
         printf("Com Lock: %d com socket: %d\n",(int)pthread_self(),sock);
         int i = 0;
         char op;
  
         if((recvMsgSize = recv((sock),rcvBuf,MAXLINE,0)) &amp;lt; 0)
         {
             perror("Erro na recepção!\n");
             exit(-1);
         }
  
         rcvBuf[recvMsgSize]='\0';
         str = (char *)rcvBuf;
  
         op = *str++;
  
         while(*str!='|' &amp;&amp; *str!=0){
             key[i]=*str;
             str++;
             i++;
         }
  
         key[++i]='\0';
         str++;
  
         if((int)op==2 || (int)op==3) strcpy(vendDev,str);  // obter o numero de produtos vendidos/devolvidos
         else strcpy(dados,str);
  
         if(op == 4 || op == 6)
         {
             db_operate(&amp;db,op,key,dados,sock); 
             pthread_mutex_unlock(&amp;mutexdb);
             printf("Unlock: %d com socket: %d\n",(int)pthread_self(),sock);
             goto start;
         }
         else
             if(op == 7)
             {
                 extract(pthreads);
                 pthread_mutex_unlock(&amp;mutexdb);
                 close(sock);
                 pthread_exit(0);
                 break;
             }
             else
                 if(op == 1 || op == 2 || op == 3 || op == 5)
                 {
                     db_search(&amp;db,op,key,vendDev,sock);
                     pthread_mutex_unlock(&amp;mutexdb);
                     printf("Unlock: %d com socket: %d\n",(int)pthread_self(),sock);
                     goto start;
                 }
     }
  </code></pre>
  
  <p></p>
  
  <p>Can anyone tell me what am i doing wrong here? How can i implement a policy where when the first thread does the unlock the next thread gains it and the said first thread returns to the waiting line, like in a FIFO list?</p>
  
  <p>Thanks ;)</p>