2011-10-24 86 views
3

我有以下代碼,它正在被SEGV信號殺死。使用調試器顯示它正在被main()中的第一個sem_init()所殺死。如果我註釋掉第一個sem_init(),第二個會導致同樣的問題。我試圖找出什麼會導致這個系統調用導致一個SEGV。 else沒有運行,所以錯誤發生在它可以返回值之前。 任何幫助將不勝感激, 謝謝。sem_init()導致SEGV

我刪除了在發生此問題之前未運行的其餘代碼。

#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"); 
+0

你錯過了一些'}',你的縮進很差。 –

+0

任何缺少}'是因爲我沒有發佈我的整個代碼。任何超出錯誤點的代碼我都覺得沒有必要發佈,這會讓這個頁面變得不必要的長。我可憐的縮進是將我的代碼粘貼到窗口中。我的格式很多都丟失了。它在我的文件中正確縮進。 – jln646v

+0

你在這裏是因爲在編寫你的代碼時,你犯了一個錯誤。發佈問題時,您隨即刪除了代碼。我們如何知道哪些錯誤是真實的,哪些是在粘貼過程中完成的?創建一個完整的,最小化的測試用例,它只展示你所問​​的問題,並且在發佈之前測試這種情況。 –

回答

5

您聲明指向你的信號燈:

sem_t* available_threads; 
sem_t* waiting_jobs; 

,但從來沒有初始化的內存。 sem_init函數不希望分配內存,只是爲了初始化現有的內存塊。分配一些內存並將這些指針指定給它,或者將信號量聲明爲sem_t並將地址傳遞給sem_init

+0

這個答案在六年後幫助我完成了一項任務。謝謝! – Driice