diff --git a/Ubung02.c b/Ubung02.c new file mode 100644 index 0000000000000000000000000000000000000000..b86ce56666e40842293a8660bd400fab0ee5aef0 --- /dev/null +++ b/Ubung02.c @@ -0,0 +1,108 @@ +// Aufgaben 1 und 2 + +#include <pthread.h> +#include <stdlib.h> +#include <stdio.h> +#include <unistd.h> + +#define NUM_THREADS 2 +#define NUM_CROSSINGS 100000 + +int cars[2]; //shared data +int cars_on_bridge = 0; +pthread_mutex_t mutex; + +void lock(pthread_mutex_t *mutex) +{ + if(pthread_mutex_lock(mutex) != 0) + { + perror("lock"); + exit(1); + } +} + +void unlock(pthread_mutex_t *mutex) +{ + if(pthread_mutex_unlock(mutex) != 0) + ; + { + perror("unlock"); + exit(1); + } +} + +void *bridge_cars (void *threadid) +{ + int car_number = *(int*) threadid; + int num_crossings = 0; + while(num_crossings < NUM_CROSSINGS) + { + lock(&mutex); + // begin of the critical section + //The block inside the if statement checks if there are no cars on the bridge, as this is where the shared variable cars_on_bridge is being accessed and modified by multiple threads. + if(cars_on_bridge == 0) + { + cars_on_bridge ++; + printf("Car %d is on the bridge.\n", car_number); + unlock(&mutex); + int crossing_time = rand() % 60 + 1; + usleep(crossing_time * 1000); + cars_on_bridge --; + lock(&mutex); + printf("Car %d leaves the bride.\n", car_number); + int cars_on_bridge = 0; + num_crossings++; + } + //end of the critical section + unlock(&mutex); + usleep(100); + } + return NULL; +} + +int main () +{ + pthread_t threads[NUM_THREADS]; + int threadid[NUM_THREADS]; + int rc; + int i; + + + //init data + srand ((unsigned) time(NULL)); + int car1 = 1; + int car2 = 2; + + //initialize mutex + if (pthread_mutex_init(&mutex, NULL) != 0) + { + perror("pthread_mutex_init"); + exit(1); + } + + + //creating threads + for(i = 0; i < NUM_THREADS; i++) + { + printf("In main: creating thread %d\n", i); + threadid[i] = i; + rc = pthread_create (&threads[i], NULL, bridge_cars, (void*)&threadid[i]); + if (rc) + { + printf("ERROR, return code from pthread_create() is %d\n", rc); + exit(1); + } + } + + for (i = 0; i < NUM_THREADS; i++) + { + pthread_join(threads[i], NULL); + } + + for(i = 0; i < 100000; i++ ) + { + usleep(100); + } + pthread_mutex_destroy(&mutex); + pthread_exit (NULL); +} \ No newline at end of file