Good afternoon everyone. I have started learning C programming and found an interesting task to put my skills to a test. To be honest it is driving me crazy and I do not have a clue how to do it. Instead of using semaphores I would like to use mutexes. I have created a program that automatically calls enter_tunnel so the car would enter. There are two directions possible - driving north ( dir == NORTH ) and driving south ( dir == SOUTH ), but I can't figure it out how to stop a car from entering a tunnel if there are cars driving towards you. I was trying to find more information how to make it work and I am not sure how to correctly use pthread_mutex_lock, pthread_mutex_unlock, pthread_mutex_signal in this context.
static int n_in_tunnel[2];
static unsigned long n_total[2];
static pthread_mutex_t tunnel_flow;
void enter_tunnel(direction_t dir) {
int mutex = pthread_mutex_init(&tunnel_flow, NULL);
assert(mutex == 0);
n_in_tunnel[dir] += 1;
// assert(n_in_tunnel[opposite(dir)] == 0);
}
void exit_tunnel(direction_t dir) {
n_in_tunnel[dir] -= 1;
n_total[dir] += 1;
}