118 lines
2.6 KiB
C
118 lines
2.6 KiB
C
// Compiler call: cc -o aufgabe1 aufgabe1.c -lpthread
|
|
#include <pthread.h>
|
|
#include <stdio.h>
|
|
//#include <stdlib.h>
|
|
#include <unistd.h>
|
|
|
|
int make_new_item(void);
|
|
void consume_item(char a, int count);
|
|
void* reader_function(void*);
|
|
void writer_function(void);
|
|
|
|
char buffer;
|
|
int buffer_has_item = 0;
|
|
pthread_mutex_t mutex;
|
|
|
|
void cleanup_resources() {
|
|
pthread_mutex_destroy(&mutex);
|
|
}
|
|
|
|
int main(int argc, char *argv[]){
|
|
pthread_mutexattr_t mutex_attr;
|
|
pthread_attr_t attr;
|
|
pthread_t reader;
|
|
int ret;
|
|
|
|
// Initialize mutex attributes
|
|
if ((ret = pthread_mutexattr_init(&mutex_attr)) != 0) {
|
|
fprintf(stderr, "Error initializing mutex attributes: %d\n", ret);
|
|
return 1;
|
|
}
|
|
|
|
// Initialize mutex
|
|
if ((ret = pthread_mutex_init(&mutex, &mutex_attr)) != 0) {
|
|
fprintf(stderr, "Error initializing mutex: %d\n", ret);
|
|
return 1;
|
|
}
|
|
|
|
// Initialize thread attributes
|
|
if ((ret = pthread_attr_init(&attr)) != 0) {
|
|
fprintf(stderr, "Error initializing thread attributes: %d\n", ret);
|
|
cleanup_resources();
|
|
return 1;
|
|
}
|
|
|
|
// Create reader thread
|
|
if ((ret = pthread_create(&reader, &attr, reader_function, 0)) != 0) {
|
|
fprintf(stderr, "Error creating thread: %d\n", ret);
|
|
cleanup_resources();
|
|
return 1;
|
|
}
|
|
|
|
writer_function();
|
|
|
|
// Wait for reader thread to finish
|
|
if ((ret = pthread_join(reader, 0)) != 0) {
|
|
fprintf(stderr, "Error joining thread: %d\n", ret);
|
|
cleanup_resources();
|
|
return 1;
|
|
}
|
|
|
|
cleanup_resources();
|
|
printf("Main thread finished!\n");
|
|
return 0;
|
|
}
|
|
|
|
void writer_function(void){
|
|
char a=0;
|
|
int count=0;
|
|
|
|
while( a != 'q' ){
|
|
pthread_mutex_lock( &mutex );
|
|
|
|
if ( !buffer_has_item ){
|
|
a = make_new_item();
|
|
buffer=a;
|
|
buffer_has_item = 1;
|
|
printf("Thread 1: buffer: '%c', loop count=%d\n", a, count);
|
|
count=0;
|
|
}
|
|
else
|
|
count++;
|
|
|
|
pthread_mutex_unlock( &mutex );
|
|
}
|
|
}
|
|
|
|
void* reader_function(void *ptr){
|
|
char a=0;
|
|
int count=0;
|
|
|
|
while(a != 'q'){
|
|
pthread_mutex_lock( &mutex );
|
|
|
|
if ( buffer_has_item ){
|
|
a=buffer;
|
|
if ( a != 'q' )
|
|
consume_item(a,count);
|
|
buffer_has_item = 0;
|
|
count=0;
|
|
}
|
|
else
|
|
count++;
|
|
|
|
pthread_mutex_unlock(&mutex);
|
|
}
|
|
printf("Reader thread finished\n");
|
|
return 0;
|
|
}
|
|
|
|
int make_new_item(){
|
|
static int buffer='a';
|
|
return buffer++;
|
|
}
|
|
|
|
void consume_item(char a, int count){
|
|
printf("Thread 2: buffer read with '%c', loop count=%d\n", a, count);
|
|
}
|