2016-07-22 75 views
-1

此刻,当我尝试使用我的线程执行decFunk进程时,出现参数3错误。我见过的例子,他们提到我需要一个无效的参数,但我不知道如何做到这一点。从void *pthreads传递参数3警告

void *decFunk(PQueue* pQ){ 
    pQ->currentProcess = pQ->firstProcess; 
    int temp = pQ->currentProcess->duration; 
    pQ->firstProcess->duration = temp -1; 

    if(pQ->currentProcess->duration == 0){ 
     pQ->firstProcess = pQ->firstProcess->next; 
    } 
    return NULL; 
} 




int main(int argc, char *argv[]) { 
    int numThreads = atoi(argv[1]); 

    sem_init(&tLock,0,0); 
    sem_init(&qLock,0,0); 

    FILE * fIn; 
    PQueue* sortQ; 
    sortQ = startQueue(); 

    printf("Enter number of threads you want to use."); 
    pthread_t threads; 

    pthread_create(&threads ,NULL , decFunk, sortQ); 


    for(t = 0; t< 5; t++){ 
     fIn = fopen("input.txt", "r"); 
     printf("Time: %d\n", t); 
     readIn(fIn, sortQ); 
     printQ(sortQ); 

     t++; 
     fclose(fIn); 
     sleep(1); 
    } 
pthread_join(&threads,NULL); 
    pthread_exit(NULL); 
    return 0; 


} 
+0

原型为'在pthread_create()'是'INT在pthread_create(的pthread_t *线程,常量pthread_attr_t * ATTR,无效*(*的start_routine) (void *),void * arg);',所以是的,'pthread_create()'的最后一个参数和你传递的函数的唯一参数是* void *',不管你是否确定那”。 – EOF

+0

我或多或少地问如何做一个空白参数,我不熟悉这一点。 – rickless

+0

只要你调用'pthread_create()'的原型时就可见,当你将'sortQ'传递给'pthread_create()'时,从'PQueue *'到'void *'的转换是隐含的。你只需要将'decFunk()'改成'void * decFunk(void * pQ)'。 – EOF

回答

0

指针转换到/由本说明书的这一部分覆盖:

§6.3.2.3指针
的指针的任何对象类型可被转换成一个 指向void并返回的指针;结果应该等于 的原始指针。

如果您将一个非void指针传递给以void *作为参数的函数,则该转换是自动的。如果您将void *分配给非空指针,转换也是自动的,反之亦然。

因此,代码中的相关内容可以写为:

#include <pthread.h> // tells the compiler that pthread_create takes a void* argument 

void *decFunk(void *arg){ 
    PQueue* pQ = arg; // implicit cast from void* back to the original pointer 

    return NULL; 
} 

int main(int argc, char *argv[]) { 

    PQueue* sortQ; 
    sortQ = startQueue(); 

    pthread_create(&threads, NULL, decFunk, sortQ); // sortQ implicitly cast to void* 

    return 0; 
} 
+0

如果表达式表示被调用函数的类型包含原型,则参数仅被转换为void *。 – EOF

+0

@EOF你是什么意思*“被调用函数的类型包含原型。”* – user3386109

+0

如果你只声明了'int pthread_create()',而不是'int pthread_create(pthread_t * thread,const pthread_attr_t * attr, void *(* start_routine)(void *),void * arg)',参数将*自动转换。 – EOF