【发布时间】:2011-12-13 20:25:15
【问题描述】:
我有以下代码,它被 SEGV 信号杀死。使用调试器表明它被 main() 中的第一个 sem_init() 杀死。如果我注释掉第一个 sem_init() ,第二个会导致同样的问题。我试图弄清楚是什么导致这个系统调用导致 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");
【问题讨论】:
-
您缺少一些
}s 并且您的缩进很差。 -
任何丢失的 }' 是因为我没有发布我的整个代码。任何超出我认为没有必要发布的错误点的代码都会使这个页面变得不必要的长。我可怜的缩进来自将我的代码粘贴到窗口中。我的很多格式都丢失了。它在我的文件中正确缩进。
-
您在这里是因为在编写代码时,您犯了一个错误。然后,您在发布问题时任意删除了代码。我们如何知道哪些错误是真实的,哪些是在粘贴过程中完成的?创建一个完整的、最小化的测试用例,仅展示您所询问的问题,并在发布之前测试是否是这种情况。
-
P-T 在我发布此消息后的一个小时内就知道我的问题是什么。
-
这并不能神奇地解决问题。 :) 学习制作测试用例并习惯它,不仅是提出问题的宝贵技能,也是执行您自己的调试时的一项宝贵技能。 P-T 之所以能够回答,是因为他在您的代码中发现了一个错误,尽管有错别字,但还是很清楚;不能保证下次会这样。
标签: multithreading pthreads semaphore segmentation-fault