dsv_dsv
dsv_dsv

Reputation: 59

Linux thread with mutex

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.

Here is my c program:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

#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(&(cond), NULL);

  int i;
  for(i = 0; i < NUM; i++){
    pthread_create(&horse[i], NULL, funHorse,(void *) &i);
  }
  pthread_create(&farmar, NULL, funFarmar, NULL);

  printf("Join farmar\n");
  pthread_join(farmar, NULL);

  for(i = 0; i < NUM; i++){
    printf("Join horse\n");
    pthread_join(horse[i], NULL);
  }

  return 0;
}

void * funHorse(void * param){

   pthread_mutex_lock(&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(&cond);
   }
   pthread_mutex_unlock(&mutex);

}


void * funFarmar(void * param){
  pthread_mutex_lock(&mutex);

  printf("Sleeping\n");
  pthread_cond_wait(&(cond),&(mutex));

  food = 20;
  printf("There are %d food \n",food);
  pthread_mutex_unlock(&mutex);
}

There is problem that horses eats only 5 times. Do not know why. If i change initialization of food to food = 2 ... result at the end is -3 (farmer does not add food).

I want to infinity loop of eating by horses and adding food by farmer.

Upvotes: 0

Views: 135

Answers (1)

mch
mch

Reputation: 9804

You are initializing cond twice: pthread_cond_t cond= PTHREAD_COND_INITIALIZER; and pthread_cond_init(&(cond), NULL);. Just remove the second one.

You do not initialize mutex: pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; should do the job. You have the mutex variable twice, remove one.

You pass the address of i to the threads, but the main thread change i. You should create an array and pass each thread another number from this array.

int number[NUM];
int i;
for(i = 0; i < NUM; i++){
  number[i]=i;
  pthread_create(&horse[i], NULL, funHorse,&number[i]);
}

you forgot to return something in the threads.

This should solve your programming errors.

Upvotes: 1

Related Questions