Like the title says, I've got a problem with the consumer thread waiting until the entire array is filled until it starts consuming, then the producer wait until it's empty again, and round they go in a circle until they're finished with their loops. I have no idea why they're doing that. Be gentle, as this is a new topic for me and I'm trying to understand mutexes and conditionals.
#include <stdio.h>
#include <pthread.h>
#define BUFFER_SIZE 6
#define LOOPS 40
char buff[BUFFER_SIZE];
pthread_mutex_t buffLock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t emptyCond=PTHREAD_COND_INITIALIZER, fullCond=PTHREAD_COND_INITIALIZER;
int buffIndex=0;
void* Producer(){
int i=0;
for(i=0;i<LOOPS;i++){
pthread_mutex_lock(&buffLock);
while(buffIndex==BUFFER_SIZE)
pthread_cond_wait(&fullCond, &buffLock);
buff[buffIndex++]=i;
printf("Producer made: %d\n", i);
pthread_mutex_unlock(&buffLock);
pthread_cond_signal(&emptyCond);
}
pthread_exit(0);
}
void* Consumer(){
int j=0, value=0;
for(j=0;j<LOOPS;j++){
pthread_mutex_lock(&buffLock);
while(buffIndex==0)
pthread_cond_wait(&emptyCond, &buffLock);
value=buff[--buffIndex];
printf("Consumer used: %d\n", value);
pthread_mutex_unlock(&buffLock);
pthread_cond_signal(&fullCond);
}
pthread_exit(0);
}
int main(){
pthread_t prodThread, consThread;
pthread_create(&prodThread, NULL, Producer, NULL);
pthread_create(&consThread, NULL, Consumer, NULL);
pthread_join(prodThread, NULL);
printf("Producer finished.\n");
pthread_join(consThread, NULL);
printf("Consumer finished.\n");
return 0;
}