线程函数不打印

Pthread function not printing

本文关键字:打印 函数 线程      更新时间:2023-10-16

我正在尝试创建一个隧道和汽车线程,模拟只有单向的隧道。假设每种方式都是 W 和 B。通往 W 的道路打开 5 秒,然后隧道再关闭 5 秒,然后隧道打开路径 B 5 秒,然后关闭另外 5 秒,然后重复。

我已经使用 tunnelf 函数创建了隧道线程,但它除了打印第一行之外什么都不做:"隧道现在对惠蒂尔绑定流量开放"。它只是有时这样做。每次我编译代码时,它要么什么都不打印,要么那行。它不会通过所需的输出。同时,如果我将完全相同的 while 循环从隧道线程放入 main,它可以工作

#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);
}   
}

值得一提的是,您永远不会防止数组溢出。在 C++17 中,您可以使用 std::size。您可以考虑使用 std::array 进行记录,这将有助于调试构建(但不是发布)

while(!in.eof() && i<std::size(record)){
in >> record[i].arrive >>record[i].bound >> record[i].cross;
//      cout <<arrive<<" " << bound<<" " << cross<<endl;
i++;
}