-1

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;
}
Nicolas
  • 33
  • 1
  • 5
  • 2
    You do not explain the design of your app, so it' not possible to recommend anything. Is each car managed by its own thread? – Martin James Dec 11 '17 at 01:27
  • 1
    Is the 'tunnel' only one lane, so cars can only be allowed on if all going in the same direction? if so, then need a count of the number of vehicles currently in the tunnel and what directory they are ALL going. If a new car is going in the same direction, increase the count and let the car in. other wise, how is the code to keep track of the number of cars trying to enter the tunnel in the opposite direction. I.E. the application needs some more analysis and the saved data needs to represent the current situation. – user3629249 Dec 11 '17 at 14:14

1 Answers1

0

There is significant literature about resolution of the problem, for example: https://docs.oracle.com/cd/E19683-01/806-6867/sync-12/index.html Also, in stack overflow, there is a question about it already: Mutex example / tutorial? And finally, here is your problem completely solved: https://www.linkedin.com/pulse/semaphore-pthread-programming-linux-purvi-pathak?articleId=7625519368425966741 I could copy the code here, but I do not want to rob the author of the solutions of his achievement.

VladP
  • 529
  • 3
  • 15