如何在读写器问题中检测饥饿
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在读写器问题中检测饥饿相关的知识,希望对你有一定的参考价值。
我对这段代码有疑问。这是经典的读者-作家问题。我遵循了在该维基百科页面上找到的伪代码,以解决第一个使作家感到饥饿的问题。我想知道我实际上如何注意到作家们正在挨饿。
我试图在不同地方放置shared_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);
答案
首先存在语法错误,writerAction和readerAction的返回类型应该为void not 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);
现在,当您运行具有大量重复次数的代码时,您将看到“编写程序正在尝试编写”,然后您将看到大量的读取程序打印输出,而不是编写程序更新共享变量的打印输出,这将证明读取程序是通过不允许更新变量来使编写者饿死。
以上是关于如何在读写器问题中检测饥饿的主要内容,如果未能解决你的问题,请参考以下文章