pthread函数的参数可以是另一个函数吗?

Anj*_*njz 4 c pthreads

我知道如何将函数作为另一个函数的参数传递.但我不知道传递给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)

cni*_*tar 7

它可以是一个函数指针,如果你愿意稍微弯曲规则.严格来说,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)

  • POSIX要求`void*`和函数指针类型具有相同的大小和表示,并且任一方向的强制转换都是值保留的.由于强制`dlsym`接口的工作方式,强制执行此要求.因此,由于POSIX线程是POSIX的一部分,因此该解决方案在该框架内完全可移植. (3认同)
  • 来源:XSH 2.12.3指针类型:*所有函数指针类型应与void指向的类型指针具有相同的表示形式.将函数指针转换为void*不得改变表示.这种转换产生的void*值可以使用显式转换转换回原始函数指针类型,而不会丢失信息.*和相应的注释:*ISO C标准不要求这样,但它是必需的用于POSIX一致性.* (2认同)