I am trying to create a tunnel and car threads that simulate a tunnel that only goes one way. Lets say each way is W and B. The way to W is open for 5 seconds, then the tunnel is closed for another 5, then the tunnel is open for way B for 5 seconds and then closed for another 5, then repeat.
I have created the tunnel thread with the tunnelf function but it does not do anything but print the first line: "The tunnel is now open to Whittier Bound traffic". And it only does that sometimes. Each time i compile the code, it can either print nothing or that line. It does not go through the required outputs. Meanwhile if i put the exact same while loop from the tunnelf thread into main, it works
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <pthread.h>
#include <conio.h>
#include <windows.h>
#include <ctime>
#include <cerrno>
#include <unistd.h>
using namespace std;
void *car(void *arg);
void *tunnelf();
static pthread_mutex_t traffic_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t car_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t bbcan = PTHREAD_COND_INITIALIZER;
static pthread_cond_t wbcan =PTHREAD_COND_INITIALIZER;
static pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
static bool whittierBound = false;
static bool bbBound = false;
struct car2{
int arrive;
int cross;
string bound;
};
int main(){
ifstream in;
in.open("Thrd.txt");
if (in.fail()){
cout<< "failed to open file";
exit(1);
}
car2 record[50];
int max_cars;
int arrive;
int cross;
string bound;
string data;
int i = 0;
in >> max_cars;
cout<<"Num cars "<<max_cars<<endl;
while(!in.eof()){
in >> record[i].arrive >>record[i].bound >> record[i].cross;
i++;
}
int size = i;
for(int i= 0; i<size; i++){
cout << record[i].arrive <<record[i].bound <<record[i].cross<<endl;
}
pthread_t cartid[max_cars];
pthread_t tunnel;//just shared variable for the tunnel
pthread_create(&tunnel, NULL, &tunnelf, NULL);
in.close();
}
void *tunnelf(){
static int done;
while(done==0){
pthread_mutex_lock(&traffic_lock);
whittierBound = true;
cout << "The tunnel is now open to Whiitier-bound traffic"<<endl;
pthread_cond_broadcast(&wbcan);
pthread_mutex_unlock(&traffic_lock);
sleep(5);
pthread_mutex_lock(&traffic_lock);
whittierBound = false;
cout << "The tunnel is now closed to all traffic"<<endl;
pthread_mutex_unlock(&traffic_lock);
sleep(5);
pthread_mutex_lock(&traffic_lock);
bbBound = true;
cout << "The tunnel is now open to Bear-Valley-bound traffic"<<endl;
pthread_cond_broadcast(&bbcan);
pthread_mutex_unlock(&traffic_lock);
sleep(5);
pthread_mutex_lock(&traffic_lock);
bbBound = false;
cout << "The tunnel is now closed to all traffic"<<endl;
pthread_mutex_unlock(&traffic_lock);
}
}