Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
5.1.c 2.22 KiB
// Aufgabe 1

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

#define NUM_THREADS     4

pthread_mutex_t lock;
pthread_cond_t cond_producer;
pthread_cond_t cond_consumer;
int item = -1;

void *producer(void *threadid) {
    long tid = (long) threadid;
    
    for (int i = 0; i < 1; i++) {
        int new_item = rand() % 100;

        pthread_mutex_lock(&lock);

        while (item != -1) {
            pthread_cond_wait(&cond_producer, &lock);
        }

        item = new_item;
        printf("Produzent #%ld: Produziert Artikel %d\n", tid, item);

        pthread_cond_signal(&cond_consumer);
        pthread_mutex_unlock(&lock);
    }

    pthread_exit(NULL);
}

void *consumer(void *threadid) {
    long tid = (long) threadid;

    for (int i = 0; i < 1; i++) {
        
        pthread_mutex_lock(&lock);

        while (item == -1) {
            pthread_cond_wait(&cond_consumer, &lock);
        }

        int consumed_item = item;
        item = -1;
        printf("Konsument #%ld: Konsumiert Artikel %d\n", tid, consumed_item);

        pthread_cond_signal(&cond_producer);
        pthread_mutex_unlock(&lock);
    }

    pthread_exit(NULL);
}

int main(int argc, char *argv[]) {
    pthread_t threads[NUM_THREADS];
    int rc;
    long t;

    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond_producer, NULL);
    pthread_cond_init(&cond_consumer, NULL);

    for (t = 0; t < NUM_THREADS / 2; t++) {
        printf("In main: creating producer thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, producer, (void *)t);
        if (rc) {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    for (t = NUM_THREADS / 2; t < NUM_THREADS; t++) {
        printf("In main: creating consumer thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, consumer, (void *)t);
        if (rc) {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    for (t = 0; t < NUM_THREADS; t++) {
        pthread_join(threads[t], NULL);
    }

    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond_producer);
    pthread_cond_destroy(&cond_consumer);
    pthread_exit(NULL);
}