简体   繁体   English

c,创建线程和线程function

[英]c, creating thread and thread function

I created dispatch_queue_thread_t struct in the headerfile.我在头文件中创建了 dispatch_queue_thread_t 结构。
This code assign the thread, task and queue to the dThread struct此代码将线程、任务和队列分配给 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;

This code is the thread functions for dispatcher_thread.这段代码是 dispatcher_thread 的线程函数。
I need to use thread in dThread to check if there is any task is assigned to it and if not need to assign the task to it.我需要在 dThread 中使用线程来检查是否有任何任务分配给它,如果不需要分配任务给它。
How do I do that?我怎么做? Is my code correct?我的代码正确吗?

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

}

No. The dThread variable in dispatcher_threadloop() isn't initialised, so it's an error to dereference it.不, dispatcher_threadloop()中的dThread变量未初始化,因此取消引用它是错误的。

It seems like you should be passing dThread to the thread function instead of dispatchQueue , as the thread function can obtain the latter from the former.似乎您应该将dThread传递给线程 function 而不是dispatchQueue ,因为线程 function 可以从前者获得后者。 Something like this (note that casting to and from void * is unnecessary):像这样的东西(请注意,没有必要在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);
}

then in the thread function:然后在线程 function 中:

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

    /* ... */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM