Skip to content
Snippets Groups Projects

Übung2

Open omah03 requested to merge omah03/alp4-repo-template:Übung2 into main
1 file
+ 49
0
Compare changes
  • Side-by-side
  • Inline
cars_1.c 0 → 100644
+ 49
0
//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
Loading