2011-08-10 138 views
1

我在头文件中创建了dispatch_queue_thread_t结构体。
该代码分配线程,任务和队列的dThread结构c,创建线程和线程函数

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"); 

} 

回答

4

号在dispatcher_threadloop()dThread变量将不会被初始化,所以这是一个错误取消对它的引用。

看来你应该将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; 

    /* ... */ 
+0

的伟大工程,感谢名单 – Leanne