Как обнаружить голод в проблеме читателя-писателя - PullRequest
0 голосов
/ 22 октября 2019

У меня есть вопрос об этом куске кода, который у меня есть. Это классическая проблема читателей-писателей. Я следовал псевдокоду, найденному на этой странице википедии, для первой проблемы, которая заставляет писателей голодать. Я хотел бы знать, как я на самом деле заметил бы голод авторов.

Я попытался поместить операторы print_variable в различные места, но это не дало мне особого понимания. Но, может быть, я просто не поняла, что происходит. Сможет ли кто-нибудь объяснить мне, как я могу визуально увидеть происходящее голодание? Спасибо! Количество попыток, которые читатель или писатель попытается прочитать или записать, задается в качестве аргумента командной строки.

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


// Compile it like so: gcc assignment2.c -lpthread


// Shared variables (semaphore and integer)
static sem_t rw_mutex;
static sem_t mutex;
static int read_count = 0;

// Shared variable
int shared_variable = 0;

static void *writerAction(void *arg){
    int number_attempt = *((int *) arg);
    int attempt = 0;
    do{
        sem_wait(&rw_mutex);
        shared_variable = shared_variable + 10;
        sem_post(&rw_mutex);
        attempt++;
    }while(attempt < number_attempt);
}

static void *readerAction(void *arg){
    int number_attempt = *((int *) arg);
    int attempt = 0;
   do{
        sem_wait(&mutex);
        read_count++;
        // waiting to be able to read for the possible writer
        if (read_count == 1 ){
            sem_wait(&rw_mutex); // get the lock so that writter can't write!
        }

        // Release the read_count variable
        sem_post(&mutex);
        sem_wait(&mutex);
        read_count--;

        if (read_count == 0){
            sem_post(&rw_mutex); // release the lock so that writter can write
        }
        sem_post(&mutex);
        attempt++;
    } while(attempt < number_attempt);
}




int main(int argc, char *argv[]) {

    int number_writers = 10;
    int number_readers = 500;
    int reader_repeat_count = atoi(argv[2]);
    int writer_repeat_count = atoi(argv[1]);

    // Instantiating the threads for the writters and readers
    pthread_t writer_threads[number_writers];
    pthread_t reader_threads[number_readers];

    // Initation of semaphores
    sem_init(&rw_mutex, 0, 1);
    sem_init(&mutex, 0, 1);

    printf("Start creation of Readers\n");
    for(int i = 0; i <number_readers; i++){
        pthread_create(&reader_threads[i], NULL, readerAction, &reader_repeat_count);
    }
    printf("Start creation of Writers\n");
    for(int i = 0; i < number_writers; i++){
        pthread_create(&writer_threads[i], NULL, writerAction, &writer_repeat_count);
    }

    // All the actions is hapenning here
    printf("Wait for Readers\n");
    for(int i = 0; i < number_readers; i++){
        printf("Waiting for : %d\n",i);
        pthread_join(reader_threads[i], NULL);
    }

    printf("Wait for Writers\n");
    // Collect all the writers
    for(int i = 0; i < number_writers; i++){
        printf("Waiting for : %d\n",i);
        pthread_join(writer_threads[i], NULL);
    }

    // Results
    printf("The shared variable is : %d\n",shared_variable);
   }

1 Ответ

0 голосов
/ 24 октября 2019

Прежде всего, существует синтаксическая ошибка, возвращаемый тип writerAction и readerAction должен быть void, а не void *

Чтобы увидеть голодание писателя, вы можете напечатать «писатель пытается написать» как раз перед тем, как писательпытается получить rw_mutex, вызов sem_wait (& rw_mutex). Добавьте еще один отпечаток, когда автор обновил переменную общего доступа внутри критического раздела. Добавьте еще один printf сразу после раздела читателя. Какой это код.

// Release the read_count variable
sem_post(&mutex);
printf("reader reading shared value %d\n", shared_variable);

Теперь, когда вы запустите код с большим числом повторов, вы увидите «писатель пытается записать», а затем вы увидите большое количество распечаток считывателя вместо того, который писатель обновляет совместно используемыми переменными,что докажет, что читатели голодают автора, не позволяя ему обновить переменную.

...