I am learning Pthread programming. Here is the question i got at the end of my assignment:
I want to copy each bytes in the source file to a new .txt
file by using producer-consumer
problem.
Here is my code structure:
void *producer(....) {
while(1){
nsleep();
read_byte(....);
nsleep();
produceToBuffer(....);
}
}
void *consumer(....) {
while(1){
nsleep();
consumeFromBuffer(....);
nsleep();
write_byte(....);
}
}
int main() {
pthread_t inThread[nIn];
pthread_t outThread[nOut];
//initialize mutex locks for all functions
pthread_mutex_init(&_mutexConsume, NULL);
pthread_mutex_init(&_mutexProduce, NULL);
pthread_mutex_init(&_mutexWrite, NULL);
pthread_mutex_init(&_mutexRead, NULL);
sem_init(&empty, 0, size); //initialize semaphore signal the empty slots available
sem_init(&full, 0, 0); //initialize semaphore full signal
for(i = 0; i < nIn; i++) {
pthread_create(inThread+i, NULL, producer, null);
}
for(j = 0; j < nOut; j++) {
pthread_create(outThread+i, NULL, consumer, null);
}
}
My question is: producer thread finish at the end of file, which is pthread_exit(0);
when the EOF detected, but for consumer thread, my thought is either finish after sleep or finish when all consumer thread are waiting semaphore full.
Can someone help me with that?