我正在尝试使用线程和互斥锁来模拟交叉点。
我有过海峡,左转,右转的功能。现在,我有一个接近十字路口的功能。这会产生一个随机的方向和转弯。每个线程共享即将到来的交叉点。
我已经为各个方向的所有汽车定义了所有锁。
采取海峡两岸功能。它有一个 switch 语句,只打印什么车当时正在做什么。现在,我只是不知道该锁定什么功能。如果汽车是朝北的方向,我会锁定东西方向,并且与汽车朝南的方向相同吗?
这是我的锁,它只是调用一个函数来锁定或解锁
#define NUMCARS 30
#define lock_NW(CAR) lock(CAR, NW_mutex)
#define lock_NE(CAR) lock(CAR, NE_mutex)
#define lock_SW(CAR) lock(CAR, SW_mutex)
#define lock_SE(CAR) lock(CAR, SE_mutex)
#define unlock_NW(CAR) unlock(CAR, NW_mutex)
#define unlock_NE(CAR) unlock(CAR, NE_mutex)
#define unlock_SW(CAR) unlock(CAR, SW_mutex)
#define unlock_SE(CAR) unlock(CAR, SE_mutex)
这是主要的
int main(int argc, char **argv){
/* Initial variables*/
int index, tid;
unsigned int carids[NUMCARS];
pthread_t carthreads[NUMCARS];
/* Start up a thread for each car*/
for(index = 0; index <NUMCARS; index++){
carids[index] = index;
tid = pthread_create(&carthreads[index], NULL, approachintersection, (void*)&carids[index]);
}
/* Wait for every car thread to finish */
for(index = 0; index <NUMCARS; index++){
pthread_join(carthreads[index], NULL);
}
printf("Done\n");
return 1;
}
这是调用函数的接近交叉点
static void * approachintersection(void* arg){
unsigned int * carnumberptr;
unsigned int carnumber;
orientation_t cardir = (orientation_t)random()%4;
unsigned long turn = random()%3;
carnumberptr = (unsigned int*) arg;
carnumber = (unsigned int) *carnumberptr;
if(turn==LEFT){
turnleft(cardir, carnumber);
} else if(turn==RIGHT){
turnright(cardir, carnumber);
} else {//straight
gostraight(cardir, carnumber);
}
return (void*)carnumberptr;
}
现在,这是我要锁定适当方向的海峡功能。
/*
cardirection - The direction the car is pointing. If it is pointing NORTH,
it is starting from the South-Eastern corner of the intersection
and "going straight" means it wants to move SOUTH to NORTH.
valid options: NORTH, SOUTH, EAST, WEST
carnumber - The car identifier
*/
static void gostraight(orientation_t cardirection, unsigned int carnumber){
switch(cardirection){
case NORTH:
printf("Car %d, Moving South-North\n", carnumber);
break;
case SOUTH:
printf("Car %d, Moving North-South\n", carnumber);
break;
case EAST:
printf("Car %d, Moving West-East\n", carnumber);
break;
case WEST:
printf("Car %d, Moving East-West\n", carnumber);
break;
}
}
所以,如果接近的汽车从南指向北,那么这辆车就是 SE 车,我会用 lock_SE(CAR) 锁定箱体东、西打印功能?防止其他线程进入和打印?所以我会锁定解锁打印语句?
还是我会锁定整个 switch 语句?
** 编辑:这会是这样做的方法吗?**
static void turnleft(orientation_t cardirection, unsigned int carnumber){
int CAR;
CAR = carnumber;
switch(cardirection){
case NORTH:
lock_SE(CAR)
printf("Car %d, Moving South-West\n", carnumber);
unlock_SE(CAR)
break;
case SOUTH:
lock_NW(CAR)
printf("Car %d, Moving North-East\n", carnumber);
unlock_NW(CAR)
break;
case EAST:
lock_SW(CAR)
printf("Car %d, Moving West-North\n", carnumber);
unlock_SW(CAR)
break;
case WEST:
lock_NE(CAR)
printf("Car %d, Moving East-South\n", carnumber);
unlock_NE(CAR)
break;
}
}