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?
Is there a reason to keep the consumer threads active after the producers are gone?
If there isn't, you can signal the consumer threads there are no more producer threads and use that as a termination signal so your main thread waits for all producer threads.
You can use pthread_join(producer_thread_id)
to wait for a producer thread to finish, and once all producer threads are done, use pthread_cancel(consumer_thread_id)
for each consumer thread to abort their execution.
You need to save each thread_id
to an array when you use pthread_create
so you can use them for pthread_cancel
and pthread_join
You can read about pthread_join
here and pthread_cancel
here