/************************************************************ File: bridge.cc Description: A program that simulates a one-lane bridge and some cars trying to get through it. Implementation of the bridge monitor. Author: Dana Vrajitoru Organization: IUSB Date: December 7, 2004 **************************************************************/ #include "bridge.h" #include using namespace std; // Simple init function setting all the values of the variables to 0. void Bridge_monitor::init() { crossing = 0; waiting_left = 0; waiting_right = 0; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond_left, NULL); pthread_cond_init(&cond_right, NULL); } // A tread is calling these when it wants to cross the bridge to the // left or right respectively. If the bridge is not free, the thread // should be waiting on the appropriate conditional variable to be // allowed to cross the bridge. void Bridge_monitor::request_left() { pthread_mutex_lock(&mutex); if (crossing || waiting_left || waiting_right) { waiting_left++; pthread_cond_wait(&cond_left, &mutex); } crossing++; pthread_mutex_unlock(&mutex); } void Bridge_monitor::request_right() { // To be completed by the student. } // A thread is calling these after it has finished crossing the // bridge. The last thread to cross should broadcast the conditional // variable in the opposite direction if any thread is waiting on it, // or the one in the same direction if not. void Bridge_monitor::release_left() { pthread_mutex_lock(&mutex); crossing--; if (crossing == 0) if (waiting_right) { pthread_cond_broadcast(&cond_right); waiting_right = 0; } else { pthread_cond_broadcast(&cond_left); waiting_left = 0; } pthread_mutex_unlock(&mutex); } void Bridge_monitor::release_right() { // To be completed by the student. }