我知道如何将函数作为另一个函数的参数传递.但我不知道传递给pthread的函数的参数是否可以是另一个函数.这甚至可能吗?
以下是编译好的示例代码,但不起作用:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_t idThread;
void aFunction(){
while(1){
fprintf(stderr,"I've been called!\n");
usleep(1000000);
}
}
void * threadFunction(void *argFunc){
// Do here some stuff;
// ...
// Now call the function passed as argument
void (*func)() = argFunc;
}
int thread_creator(void(*f)()){
// I want to use as argument for threadFunction the f function
pthread_create(&idThread, NULL, threadFUnction, (void *)f);
}
int main(){
thread_creator(aFunction);
while(1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它可以是一个函数指针,如果你愿意稍微弯曲规则.严格来说,a void *不能保证能够保存函数指针.像这样(未经测试):
void some_fun()
{
/* ... */
}
void thread_fun(void *arg)
{
void (*fun)() = arg;
}
pthread_create(...., (void *) some_fun);
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您还需要通过函数指针调用该函数.就像是:
void (*func)() = argFunc;
funct(); /* <-- */
Run Code Online (Sandbox Code Playgroud)