将函数指针传递给pthread_create函数的arg

时间:2018-04-23 08:50:59

标签: c linux pthreads function-pointers

我有一个函数void startScanner(...)将两个函数指针作为参数:userType *vConfig(void)void * vCallback(void)。在这个函数中,我想创建一个线程并在创建的函数线程中调用vCallback()函数。所以我决定将vCallback作为args传递给pthreadcreate。 startScanner函数的代码:

void startScanner(tUsrStatus (*vConfig)(), void* (vCallback)()){

    if(pthread_create(&scannerThread, NULL, scannerThreadFunc, vCallback))
    {
        printf("Thread creation fails!\n");
    }
}

scannerTread功能:

static void *scannerThreadFunc(void *arg()){

    void *funcptr(void) = arg;

    while(1)
    {
        funcptr();
    }
    pthread_exit(NULL);
}

我收到以下错误:

error: function ‘funcptr’ is initialized like a variable
error: nested function ‘funcptr’ declared but never defined

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

语法错误(*),标准C中的不可能传递let jsonString = message.arguments[0] as! String //Instead of string Describing 中的函数指针。指向函数的指针和指向数据的指针之间存在根本区别,它们无法相互转换。这是因为可能存在一些平台,其中函数和数据指针在大小上会有所不同,或者指向不同的地址空间,或者其他什么。

但是,当然,有一种简单的方法可以实现你想要的:将你的函数指针放在void *里面并传递指针。

struct

添加错误检查等。

(*)至于你得到的具体错误,函数指针需要围绕标识符的parantheses,所以而不是

typedef (*callback)(void);

typedef struct threadargs
{
    callback cb;
} threadargs;

void mycallback(void)
{
    // ...
}

void *threadfunc(void *arg)
{
    threadargs *ta = arg;

    // call your callback:
    ta->cb();

    return ta; // or: return 0, or some pthread_exit(), ...
}

int main(void)
{
    pthread_t thread;
    threadargs ta = { mycallback };
    pthread_create(&thread, 0, threadfunc, &ta);

    // make sure "ta" lives for as long as the thread executes,
    // here just wait until it exits:
    pthread_join(&thread, 0);
}

你必须写

void *funcptr(void) = arg;

为方便使用函数指针,void (*funcptr)(void) = arg; 它们很常见,如上例所示。无论如何,如上所述,这不会解决你的问题。

相关问题