gpt4 book ai didi

c - 将指针传递给 pthread_create 中的函数

转载 作者:行者123 更新时间:2023-11-30 15:53:58 27 4
gpt4 key购买 nike

我试图通过传递函数指针来创建线程,但是在这一行

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;

}

最佳答案

问题是您对 start_thread 的声明,它需要一个 void* 而不是函数指针。

将其更改为:

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

该函数指针类型的 typedef 将简化该原型(prototype)和数组声明。

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

关于c - 将指针传递给 pthread_create 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405345/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com