c,创建线程和线程功能

时间:2011-08-10 04:55:09

标签: c multithreading struct pthreads

我在头文件中创建了dispatch_queue_thread_t结构 此代码将线程,任务和队列分配给dThread结构

dispatch_queue_thread_t *dThread;
dThread = (dispatch_queue_thread_t *) malloc(sizeof(dispatch_queue_thread_t));

pthread_t dispatcher_thread;

if(pthread_create(&dispatcher_thread, NULL, dispatcher_threadloop, (void *)dispatch_queue)){
        perror("ERROR creating thread."); exit(EXIT_FAILURE);
}

dThread->task=NULL;
dThread->queue=dispatch_queue;
dThread->thread=dispatcher_thread;

此代码是dispatcher_thread的线程函数 我需要在dThread中使用线程来检查是否有任何任务分配给它,如果不需要将任务分配给它。
我怎么做? 我的代码是否正确?

  void *dispatcher_threadloop(void * queue){

//thread loop of the dispatch thread- pass the tast to one of worker thread
dispatch_queue_t *dQueue;
dQueue=queue;

//can I do this?
dispatch_queue_thread_t *dThread;

printf("message-boss1");
dQueue = (dispatch_queue_t *)queue;
if (dQueue->HEAD!=NULL){
    for(;;){
        sem_wait(dQueue->queue_task_semaphore);
        dThread->task = dQueue->HEAD;
        dQueue->HEAD =  dQueue->HEAD->next;
        dQueue->HEAD->prev = NULL;
        sem_post(dQueue->queue_task_semaphore);

        //TODO
    }
}

printf("message-boss2");

}

1 个答案:

答案 0 :(得分:4)

没有。 dThread中的dispatcher_threadloop()变量未初始化,因此取消引用它是错误的。

似乎你应该将dThread传递给线程函数而不是dispatchQueue,因为线程函数可以从前者获得后者。这样的事情(请注意,不需要在void *之间进行投射):

dispatch_queue_thread_t *dThread;
dThread = malloc(sizeof *dThread);

dThread->task = NULL;
dThread->queue = dispatch_queue;

if (pthread_create(&dThread->thread, NULL, dispatcher_threadloop, dThread)) {
    perror("ERROR creating thread.");
    exit(EXIT_FAILURE);
}

然后在线程函数中:

void *dispatcher_threadloop(void *arg)
{
    dispatch_queue_thread_t *dThread = arg;
    dispatch_queue_t *dQueue = dThread->queue;

    /* ... */