From 3f9b265317cda92f1deeeb3d0e664b153b726fc5 Mon Sep 17 00:00:00 2001 From: omah03 <omah03@mi.fu-berlin.de> Date: Mon, 8 May 2023 13:20:22 +0000 Subject: [PATCH] Teil 1) --- cars_1.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 cars_1.c diff --git a/cars_1.c b/cars_1.c new file mode 100644 index 0000000..54f8b01 --- /dev/null +++ b/cars_1.c @@ -0,0 +1,49 @@ +//Code compiles but without protection + + +#include <stdio.h> +#include <stdlib.h> +#include <pthread.h> +#include <unistd.h> +#include <sys/wait.h> + +#define crosses 100 +int car_on_bridge = 0; + +void* func(void* arg){ + int car_id = *(int*)arg; + int crosses_counter = 0; + while (crosses_counter < crosses){ + while (car_on_bridge == 1){ + } + printf("Car %d is crossing the bridge\n",car_id); + car_on_bridge ++; + usleep(10000); + car_on_bridge --; + printf("Car %d is crossing the bridge\n", car_id); + + crosses_counter++; + } + return NULL; +} + +int main(){ + pthread_t threads[2]; + int thread_id[2] = {0,1}; + + for (int i = 0; i < 2; i++){ + if (pthread_create(&threads[i],NULL,func,&thread_id[i])!=0){ + printf("Error creating thread"); + exit(1); + } + } + for (int i = 0; i < 2; i++){ + if (pthread_join(threads[i],NULL)!=0){ + printf("Error joining threads"); + exit(1); + } + } + printf("All cars have crossed %d times!",crosses); + return 0; + +} \ No newline at end of file -- GitLab