我使用pthreads在C中实现了一个问题,它是一个从东到西穿过河流的旧桥。由于它是一座小桥,汽车只能去 在一个方向。 我已经解决了创建将穿过桥梁(使用关键区域)的线程的问题,如果桥上没有车辆或者车辆穿越方向相同,它们会交叉。 下一步是制作另一个必须在整个过程中运行的线程,这个线程必须允许在一个方向上传递到一定数量的汽车,然后到另一个方向,就像警察那样。现在我正在做以下事情: 我正在创建一个帖子(警察):
pthread_create(&policeOfficer, NULL, officerFunction, &bridge);
在创造"汽车之前#34;线程:
pthread_t thread[totalCars];
int randomDir;
int contWest = 0;
int contEast = 0;
while (contWest + contEast < totalCars) {
randomDir = (int) (rand() % 2); //random number to define the direction (east/west)
if (contWest < westCars && randomDir == 1) {
contWest++;
//sleep(1);
pthread_create(&thread[(contWest + contEast) - 1], NULL, west, &bridge);
} else if (contEast < eastCars && randomDir == 0) {
contEste++;
//sleep(1);
pthread_create(&thread[(contwest + contEast) - 1], NULL, east, &bridge);
}
}
&#34;官员&#34;执行如下(这不起作用):
static void* officer(void *data) {
bridge *pBridge = (bridge *) data;
while(totalThreads>=0){
while(pBridge->numberOfCars <= carsAllowed);//busy waiting I think. numberOfCars is the actual number of cars at the bridge (crossing)
if(pBridge->direction == WEST){
pBridge->direction = EAST;
}else{
pBridge->direction = WEST;
}
}
return NULL;
}
我习惯于使用线程和线程数组,但不习惯使用线程来控制其他线程,因此我不知道这是否正确。控制线程如何使用桥接器的功能都在工作,所以我不认为我需要修改它们。 我认为&#34;官员&#34;只需要允许一定数量的汽车在一个方向或另一个方向上交叉(在汽车通过后改变桥梁方向)所以我希望你能帮助我解决这个问题。 谢谢!