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

Merge branch 'Übung2Omar' into 'Übung2'

Cars

See merge request omah03/alp4-repo-template!6
parents 6700c19e 2b183b54
Branches
Tags
1 merge request!4Übung2
cars_1.c 0 → 100644
//Code compiles with protection but doesn't work correctly
// Used two fold lock with mutal precedence
//Aufgabe 1
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define crosses 100000
#define Car_Number 5 //Change car number here as you wish
#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 % Car_Number]==0){ //We ensure that the index of lock array is within 0-car_number -1
sleep(100);
}
return 0;
}
int unlock(int thread_id){
_lock[thread_id % 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 is crossing 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**********//
/*The thread acquires the lock before it enters the ciritical section.
If there is a car on the bridge (another thread has the lock) then we wait.
While the car is crossing, we increment he car_on_bridge by 1, reaching bridge capacity.
We simulate the crossing bridge time using usleep.The car crosses, we decrement the car_on_bridge and print out a message that the car has crossed, then we increment the crosses_counter and release the lock so that it can be obtained by other cars(threads).*/
}
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