realtime/ex07/aufgabe5.c

73 lines
1.9 KiB
C

// Compiler call: gcc -o aufgabe1 aufgabe1.c -lpthread
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#define LOOPCOUNT 200
void* reader_function(void*);
void writer_function(void);
int buffer_a, buffer_b;
pthread_mutex_t mutex_a, mutex_b;
int main(int argc, char* argv[]) {
pthread_mutexattr_t mutex_attr;
pthread_attr_t attr;
pthread_t reader;
// Initialize mutex attributes
if (pthread_mutexattr_init(&mutex_attr) == 0) {
// Set the mutex protocol to PCP
pthread_mutexattr_setprotocol(&mutex_attr, PTHREAD_PRIO_PROTECT);
// Set the priority ceiling for each mutex
pthread_mutexattr_setprioceiling(&mutex_attr, 10); // Example priority ceiling
if (pthread_mutex_init(&mutex_a, &mutex_attr) == 0) {
if (pthread_mutex_init(&mutex_b, &mutex_attr) == 0) {
if (pthread_attr_init(&attr) == 0) {
// Create the reader thread
if (pthread_create(&reader, &attr, reader_function, 0) == 0) {
writer_function();
pthread_join(reader, 0);
}
}
pthread_mutex_destroy(&mutex_b);
}
pthread_mutex_destroy(&mutex_a);
}
}
printf("Main thread finished!\n");
return 0;
}
void writer_function(void) {
int i;
for (i = 0; i < LOOPCOUNT; i++) {
pthread_mutex_lock(&mutex_a);
buffer_a = i;
printf("Writer: Buffer a is : %d,\n", buffer_a);
pthread_mutex_lock(&mutex_b);
buffer_b = buffer_a;
printf("Writer: Buffer b is : %d,\n", buffer_b);
pthread_mutex_unlock(&mutex_b);
pthread_mutex_unlock(&mutex_a);
}
}
void* reader_function(void* ptr) {
int i;
for (i = 0; i < LOOPCOUNT; i++) {
pthread_mutex_lock(&mutex_a);
printf("Reader: Buffer a+b is : %d,\n", buffer_b + buffer_a);
pthread_mutex_unlock(&mutex_a);
pthread_mutex_lock(&mutex_b);
printf("Reader: Buffer a is : %d,\n", buffer_a);
pthread_mutex_unlock(&mutex_b);
}
printf("Reader thread finished\n");
return 0;
}