#Concept check - using conditional variable and mutex lock on readers-writers problem

4 messages · Page 1 of 1 (latest)

proud radish
#

This is my attempt. But I am not so sure if the conditional variable and mutex lock is applied correctly.

#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t readers_cv, writers_cv;
int readers_count = 0;

void Reader() {
    pthread_mutex_lock(&mutex);
    readers_count++;
    if (readers_count == 1) {
        pthread_mutex_lock(&writers_cv);
    }
    pthread_mutex_unlock(&mutex);
    
    // Perform reading
    
    pthread_mutex_lock(&mutex);
    readers_count--;
    if (readers_count == 0) {
        pthread_cond_signal(&writers_cv);
    }
    pthread_mutex_unlock(&mutex);
}

void Writer() {
    pthread_mutex_lock(&mutex);
    while (readers_count > 0) {
        pthread_cond_wait(&writers_cv, &mutex);
    }
    
    // Perform writing
    
    pthread_mutex_unlock(&mutex);
}
whole nicheBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

proud radish
#

Call for help. Still open

whole nicheBOT
#

This question is being automatically marked as stale.
If your question has been answered, type !solved.
If your question is not answered feel free to bump the post or re-ask.
Take a look at !howto ask for tips on improving your question.