title: Linux thread with mutex
body: <p>Hi I have program which simulate horse farm, there are some place with food and some horses, horse eats food. If there are not food horse give signal to farmer and he add more food.</p>
  
  <p>Here is my c program:</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  
  #define NUM 5
  
  pthread_cond_t cond= PTHREAD_COND_INITIALIZER;
  
  long food;
  
  pthread_mutex_t mutex;
  
  pthread_t horse[NUM];
  
  pthread_t farmar;
  
  pthread_mutex_t mutex;
  
  
  void * funHorse(void *);
  void * funFarmar(void *);
  
  int main(int argc, char * argv[]){
  
    food = 10;
  
    pthread_cond_init(&amp;(cond), NULL);
  
    int i;
    for(i = 0; i &lt; NUM; i++){
      pthread_create(&amp;horse[i], NULL, funHorse,(void *) &amp;i);
    }
    pthread_create(&amp;farmar, NULL, funFarmar, NULL);
  
    printf("Join farmar\n");
    pthread_join(farmar, NULL);
  
    for(i = 0; i &lt; NUM; i++){
      printf("Join horse\n");
      pthread_join(horse[i], NULL);
    }
  
    return 0;
  }
  
  void * funHorse(void * param){
  
     pthread_mutex_lock(&amp;mutex);
     int index = *((int*) param);
     food--;
     printf("Eating horse number %d there are %d food \n",index,food);
     sleep(1);
     if(food == 0){
       printf("Horse number %d is hungry\n",index);
       pthread_cond_signal(&amp;cond);
     }
     pthread_mutex_unlock(&amp;mutex);
  
  }
  
  
  void * funFarmar(void * param){
    pthread_mutex_lock(&amp;mutex);
  
    printf("Sleeping\n");
    pthread_cond_wait(&amp;(cond),&amp;(mutex));
  
    food = 20;
    printf("There are %d food \n",food);
    pthread_mutex_unlock(&amp;mutex);
  }
  </code></pre>
  
  <p>There is problem that horses eats only 5 times. Do not know why. If i change initialization of food to <code>food = 2</code> ... result at the end is -3 (farmer does not add food).</p>
  
  <p>I want to infinity loop of eating by horses and adding food by farmer.</p>