c - 是什么导致线程等待?
问题描述
这段代码还没有完成,所以知道它应该只打印出这些行。但我不知道是什么锁定了第一个P( direc_sem );
#include <sys/types.h>
#include <sys/ipc.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include "sem_ops.h"
#include <semaphore.h>
#define MAXCARS 5
#define MAXWAIT 20
#define CROSSINGTIME 4
int G_direction = 0, direc_sem, car_E;
int carNum;
int retVal=0, lower = 0, upper = 1;
int car_rid[MAXCARS];
pthread_t threads[MAXCARS];
const char* printRandoms()
{
int num = (rand() % (upper - lower + 1)) + lower;
if (num == 0){
//left headed west
return "west";
}else return "east";
//return num;
}
void *car(void *arg) {
int carNum = (int)(intptr_t)arg; //what car is it
const char* direction = printRandoms(); //random direction
printf(" car no %d is idling, planning to go %s \n",carNum, direction);// test print
sleep( rand() % MAXWAIT ); // wait a random amounnt of time
//P( reader_sem );
//readers++;
//if( readers == 1 )
// P( counter_sem );
//V( reader_sem );
P( direc_sem );
if (G_direction >=0){
G_direction++;//->> move on to bridge
if (G_direction == 1){//if first car on bridge lock other traffic
P(car_E);
}else {
printf("stuck");
}
}
V(direc_sem);
printf("car no %d goes on the bridge heading %s \n", carNum,direction);
sleep(CROSSINGTIME);
printf("car no %d goes off the bridge heading %s \n", carNum, direction);
P(direc_sem);
G_direction--;//->> move off the bridge
if (G_direction == 0){//if last car on bridge unlock other traffic
V(car_E);
}
V(direc_sem);
//bridge no longer empty
// printf("W car# %d => %d\n", carNum, G_direction);//print test
// }// wait till westbound car is free
}
void Truck(){
}
int main( void ){
direc_sem = semtran( IPC_PRIVATE );
car_E = semtran( IPC_PRIVATE );
for (int i = 0; i < MAXCARS; i++){
retVal = pthread_create(&threads[i], NULL,car ,(void *)(intptr_t)i);
if(retVal!=0){
printf("pthread_create failed in %d_th pass\n",i);
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < MAXCARS; i++){
retVal = pthread_join(threads[i], NULL);
if(retVal!=0){
printf("pthread_join failed in %d_th pass\n",i);
exit(EXIT_FAILURE);
}
}
//sem_destroy(&carLock);
return 0;
}
解决方案
用错误的文件编译肯定已经太久了谢谢
推荐阅读
- javascript - 在 React 中重用组件逻辑
- javascript - 把一个函数变成promise似乎行不通
- activemq-artemis - Artemis:使用 CLI 计数消息
- json - 当它可以是单个字符串或使用 Newtonsoft 的 jarray 时,反序列化 JSON 属性
- vue.js - 必须在 vue-router 上单击两次
- python - 如果在 Flask 中为 false,如何重新访问相同的视图函数
- html - 在 bootsrap 4 卡中使用图像作为背景
- python - python中的类属性和子类关系
- search - 将查询函数放入可以通过按钮激活的脚本中
- javascript - Cloud Function 的 Cloud Firestore 触发器