c,pthread_create 给出段错误?

标签 c multithreading pthreads segmentation-fault

我在创建线程并在结构中声明一些变量时不断收到段错误...
有谁知道为什么吗?

dispatch_queue_t *dispatch_queue_create(queue_type_t queueType){

int cores = num_cores();
printf("message-queuecreate1");

dispatch_queue_t *dispatch_queue = (dispatch_queue_t *) malloc(sizeof(dispatch_queue_t));
dispatch_queue->HEAD = NULL;
dispatch_queue->END = NULL;

//create a thread array for dispatcher and worker threads
dispatch_queue_thread_t *threads[cores+1];
threads[cores+1]= (dispatch_queue_thread_t *)malloc(sizeof(dispatch_queue_thread_t));

//create semaphores
sem_t queue_task_semaphore;
sem_t queue_thread_semaphore;
sem_t queue_wait_semaphore;

sem_init(&queue_task_semaphore, 0, 1);
sem_init(&queue_thread_semaphore,0,1);
sem_init(&queue_wait_semaphore,0,1);

dispatch_queue->queue_task_semaphore = queue_task_semaphore;
dispatch_queue->queue_thread_semaphore = queue_thread_semaphore;
dispatch_queue->queue_wait_semaphore = queue_wait_semaphore;




//create dispatcher thread      
//segmentation fault #1////////////////
threads[0]->current_task=NULL;
threads[0]->queue=dispatch_queue;

pthread_create(threads[0]->thread, NULL, dispatcher_threadloop, threads[0]);
//////////////////////////////////////  

if (queueType == CONCURRENT){
    int i = 0;
    int thread_id=0;
    //create worker thread array if the type of the queue is concurrent

    while(i<cores){

        //create worker thread

        thread_id = i+1;

        //segmentation fault #2//////////
        threads[i+1]->queue=dispatch_queue;
        threads[thread_id]->thread=NULL;
        threads[thread_id]->current_task=NULL;

        pthread_create(threads[thread_id]->thread, NULL, worker_threadloop, (void *)(long)i);
        ////////////////////////////////

        printf("thread %d is created\n",i);
        i++;
    }

} else {//do smth}
    //segmentation fault# 3////////////////
    threads[1]->thread=worker_thread;
    threads[1]->queue=dispatch_queue;
    threads[1]->current_task=NULL;
    //////////////////////////////////////
}



return dispatch_queue;

}

最佳答案

你的代码充满了问题:

访问threads[core + 1]无效。此外,您没有为 threads[0] ... threads[core] 分配内存。

dispatch_queue_thread_t *threads[cores+1];
threads[cores+1]= ....;

所以这些都会失败:

threads[0]->current_task=NULL; /* See above. */

threads[i+1]->queue=dispatch_queue; /* Again, no memory allocated. */


可能还有其他问题,但我会首先削减 cores+1 内容并将其替换为:

for (i = 0; i < cores; i++) {
    threads[i] = malloc(sizeof(*threads[i]));
}

关于c,pthread_create 给出段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7007703/

相关文章:

检查文本文件中是否有新行

c - C代码中的字母顺序错误

java - 何时使用 SwingUtilities.invokeAndWait/invokeLater

c++ - 在提升线程中调用 pthread_getspecific 时访问错误

c - gdb 没有正确打印字符串值

c - 在 C 程序中禁用中断

c - 具有常量成员的结构的内存分配

c++ - 我可以在 MFC 中有多个 GUI 线程吗?

multithreading - 无线程窗口Visual Studio 2010 Ultimate

c - pthread_join() 在压力测试中挂起