0

関数ポインターを渡してスレッドを作成しようとしていますが、この行で

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;

}
4

2 に答える 2

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];
于 2012-11-15T20:16:22.443 に答える
0

あなたの関数は次のように機能しますvoid*

pthread_t start_thread(void *func, thread_data *tdata)

そして、それを 3 番目の引数として pthread_create に渡します。void *(*) (void *)

于 2012-11-15T20:16:02.623 に答える