首页 > 解决方案 > 是什么导致线程等待?

问题描述

这段代码还没有完成,所以知道它应该只打印出这些行。但我不知道是什么锁定了第一个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;
}

标签: cmultithreadingposixsemaphore

解决方案


用错误的文件编译肯定已经太久了谢谢


推荐阅读