sem_init()导致SEGV

时间:2011-10-24 04:22:55

标签: multithreading pthreads semaphore sigsegv

我有以下代码,它被SEGV信号杀死。使用调试器显示它被main()中的第一个sem_init()杀死。如果我注释掉第一个sem_init(),第二个会导致同样的问题。我试图找出导致这个sys调用导致SEGV的原因。 else没有运行,所以错误发生之前它可以返回一个值。 任何帮助将不胜感激, 谢谢。

我删除了在出现此问题之前未运行的其余代码。

#define PORTNUM 7000
#define NUM_OF_THREADS 5
#define oops(msg) { perror(msg); exit(1);}
#define FCFS 0
#define SJF 1;

void bindAndListen();
void acceptConnection(int socket_file_descriptor);
void* dispatchJobs(void*);
void* replyToClient(void* pos);

//holds ids of worker threads
pthread_t threads[NUM_OF_THREADS];

//mutex variable for sleep_signal_cond
pthread_mutex_t sleep_signal_mutex[NUM_OF_THREADS];
//holds the condition variables to signal when the thread should be unblocked
pthread_cond_t sleep_signal_cond[NUM_OF_THREADS];

//mutex for accessing sleeping_thread_list
pthread_mutex_t sleeping_threads_mutex = PTHREAD_MUTEX_INITIALIZER;
//list of which threads are sleeping so they can be signaled and given a job
std::vector<bool> *sleeping_threads_list = new std::vector<bool>();

//number of threads ready for jobs
sem_t* available_threads;
sem_t* waiting_jobs;


//holds requests waiting to be given to one of the threads for execution
std::vector<std::vector<int> >* jobs = new std::vector<std::vector<int> >();

pthread_mutex_t jobs_mutex = PTHREAD_MUTEX_INITIALIZER;




int main (int argc, char * const argv[]) {

//holds id for thread responsible for removing jobs from ready queue and assigning them to worker thread
pthread_t dispatcher_thread;


//initializes semaphores
    if(sem_init(available_threads, 0, NUM_OF_THREADS) != 0){          //this is the line causing the SEGV
        oops("Error Initializing Semaphore");
    }

    if(sem_init(waiting_jobs, 0, 0) !=0){
        oops("Error Initializing Semaphore");
    }


//initializes condition variables and guarding mutexes
for(int i=0; i<NUM_OF_THREADS; i++){
    pthread_cond_init(&sleep_signal_cond[i], NULL);
    pthread_mutex_init(&sleep_signal_mutex[i], NULL);
}




if(pthread_create(&dispatcher_thread, NULL, dispatchJobs, (void*)NULL) !=0){
    oops("Error Creating Distributer Thread");

1 个答案:

答案 0 :(得分:5)

您声明指向信号量的指针:

sem_t* available_threads;
sem_t* waiting_jobs;

但永远不会初始化内存。 sem_init函数不期望分配内存,只是为了初始化现有的内存块。分配一些内存并将这些指针分配给它,或将信号量声明为sem_t并将地址传递给sem_init