//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
intcar_on_bridge=0;
char_lock[Car_Number];
intlock(intthread_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);
}
return0;
}
intunlock(intthread_id){
_lock[thread_id%Car_Number]=0;
return0;
}
void*func(void*ptr){
intcar_id=*(int*)ptr;
intcrosses_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).*/