2012-11-15 71 views
0

我試圖通過傳遞函數指針創建一個線程的功能,但在這行傳遞指針,指向在pthread_create

pthread_t start_thread(void *func, thread_data *tdata) 

它給了我 -

use-hello.c:23: error: invalid conversion from 'void*' to 'void* (*)(void*)  

任何輸入,請.. 。

typedef struct thread_data{ 
int fd; 
int threadId; 
}thread_data; 


pthread_t start_thread(void *func, thread_data *tdata) 
{ 
    pthread_t thread_id; 
    int rc; 
     printf("In main: creating thread\n"); 
     rc = pthread_create(&thread_id, NULL, func, tdata); 
     if (rc){ 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
     exit(-1); 
     } 
    return(thread_id); 
} 


void thread_function1(thread_data *tdata){ 
. 
. 
} 

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

/* Our file descriptor */ 
int fd; 
int rc = 0; 

printf("%s: entered\n", argv[0]); 

/* Open the device */ 
fd = open("/dev/hello1", O_RDWR); 

if (fd == -1) { 
    perror("open failed"); 
    rc = fd; 
    exit(-1); 
} 
printf("%s: open: successful, fd=%d\n", argv[0], fd); 

//array of function pointers 
void (*function[5])(thread_data*); 

function[0] = thread_function0; 
function[1] = thread_function1; 
function[2] = thread_function2; 
function[3] = thread_function3; 
function[4] = thread_function4; 


//start threads 
for(int i=0; i<2; i++){ 
    thread_data *tdata[i] = (thread_data*)malloc(sizeof(thread_data)); 
    tdata[i]->threadId = i; 
    tdata[i]->fd = fd; 
    printf("starting thread = %d\n",start_thread(function[i]), tdata[i])); 
} 

while(1) sleep(1); // infinite loop 

printf("closing file descriptor..\n"); 
close(fd); 
printf("file descriptor closed..\n"); 

return 0; 

} 
+0

'pthread_create'的第三個參數必須是'無效*(*的start_routine)(無效*)',並嘗試將它傳遞一個'無效*'。一個'void *'可以隱式轉換爲指向任何對象類型的指針,但不是函數指針。 –

回答

0

你的函數需要FUNC動作void*

pthread_t start_thread(void *func, thread_data *tdata) 

然後你將它傳遞給pthread_create這應該是void *(*) (void *)

1

的問題是你的start_thread聲明作爲第三個參數,它需要一個void*,而不是一個函數指針。

將其更改爲:

pthread_t start_thread(void *(*func) (thread_data *), thread_data *tdata); 

,一種在函數指針類型將簡化這兩個原型和你的數組聲明的typedef。

typedef void (*thread_func)(thread_data*); 
pthread_t start_thread(thread_func func, thread_data *tdata); 
thread_func function[5]; 
+0

非常感謝Mat,Kylo和Daniel。 – Sundevil

相關問題