diff --git a/cars_1.c b/cars_1.c new file mode 100644 index 0000000000000000000000000000000000000000..54f8b01ac9ccf664ee1ad49377a3d838aa5b92f9 --- /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