Skip to content
Snippets Groups Projects
Commit f8ef7fb7 authored by omah03's avatar omah03
Browse files

Teil 2)

parent d68f3bd0
No related branches found
No related tags found
1 merge request!4Übung2
cars_2.c 0 → 100644
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define crosses 100000
#define Car_Number 2
#define Bridge_Capacity 1
int car_on_bridge = 0;
char _lock[Car_Number];
int lock (int thread_id){
_lock[thread_id] = 1;
while (_lock[(thread_id + 1) % Car_Number] == 1){
usleep(100);
}
return 0;
}
int unlock(int thread_id){
_lock[(thread_id + 1) % Car_Number] = 0;
return 0;
}
void* func(void* ptr){
int car_id = *(int*)ptr;
int crosses_counter = 0;
//**********CRITICAL SECTION**********//
while (crosses_counter < crosses){
lock(car_id);
while (car_on_bridge == Bridge_Capacity){}
printf("Car %d has crossed the bridge\n",car_id);
car_on_bridge ++;
usleep(10000);
car_on_bridge --;
printf("Car %d has crossed the bridge\n", car_id);
crosses_counter++;
unlock(car_id);
//**********CRITICAL SECTION**********//
}
return NULL;
}
int main(){
pthread_t threads[Car_Number];
int thread_id[Car_Number];
for (int i = 0; i < Car_Number; i++){
thread_id[i] = i;
if (pthread_create(&threads[i],NULL,func,&thread_id[i])!=0){
printf("Error creating thread");
exit(1);
}
}
for (int i = 0; i < Car_Number; i++){
if (pthread_join(threads[i],NULL)!=0){
printf("Error joining threads");
exit(1);
}
}
printf("All cars have crossed %d times!",crosses);
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment