2016-07-22 32 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