Я пытаюсь написать программу pthread для проблемы читателей и писателей с равным приоритетом читателя и писателя (когда есть один писатель и один читатель, оба должны иметь одинаковую вероятность выполнения операции (чтение или запись)). Ниже приведена моя реализация.
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t lock;
pthread_mutex_t empty;
pthread_mutex_t wChance;
int readers = 0;
pthread_t tid[4];
int sharedNumber = 0;
void test() { printf("Fuck Off"); }
void *readToInt(void *arg) {
int i = 0;
while (i < 10) {
i++;
int a = *((int *)arg);
pthread_mutex_lock(&wChance);
pthread_mutex_unlock(&wChance);
pthread_mutex_lock(&lock);
readers++;
if (readers == 1) {
pthread_mutex_lock(&empty);
}
pthread_mutex_unlock(&lock);
printf("Thread %d started reading the resource \n", a);
printf("Value read by thread %d is %d \n", a, sharedNumber);
int i = 0;
test();`enter code here`
for (i = 0; i < 100000; i++)
;
printf("Thread %d finished reading the resource \n", a);
pthread_mutex_lock(&lock);
readers--;
if (readers == 0) {
pthread_mutex_unlock(&empty);
}
pthread_mutex_unlock(&lock);
}
return NULL;
}
void *writeToInt(void *arg) {
int i = 0;
while (i < 10) {
i++;
int a = *((int *)arg);
pthread_mutex_lock(&wChance);
pthread_mutex_lock(&empty);
printf("Thread %d started writing to the resource \n", a);
printf("Number of readers in the system is %d", readers);
sharedNumber = a;
test();
printf("Value written by thread %d is %d \n", a, sharedNumber);
int i = 0;
for (i = 0; i < 100000; i++)
;
printf("Thread %d finished writing the resource \n", a);
pthread_mutex_unlock(&wChance);
pthread_mutex_unlock(&empty);
}
return NULL;
}
int main() {
printf("Fuck here");
if (pthread_mutex_init(&lock, NULL) != 0 || pthread_mutex_init(&empty, NULL) != 0 ||
pthread_mutex_init(&wChance, NULL) != 0) {
printf("\n mutex init failed\n");
return 0;
}
int *arg0 = malloc(sizeof(*arg0));
*arg0 = 0;
int *arg1 = malloc(sizeof(*arg1));
*arg1 = 1;
int *arg2 = malloc(sizeof(*arg2));
*arg2 = 2;
int *arg3 = malloc(sizeof(*arg3));
*arg3 = 3;
int err = pthread_create(&(tid[0]), NULL, &readToInt, arg0);
err = pthread_create(&(tid[1]), NULL, &readToInt, arg1);
err = pthread_create(&(tid[2]), NULL, &writeToInt, arg2);
err = pthread_create(&(tid[3]), NULL, &readToInt, arg3);
if (err != 0) {
printf("\ncan't create thread :[%s]", strerror(err));
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
pthread_join(tid[3], NULL);
return 0;
}
Однако этот код всегда выбирал авторов (приоритет писателя). Как я могу сделать этот равный приоритет для читателей и писателей?