pthread_create() 调用的函数的多个参数 - 参数是函数指针

Multiple arguments to function called by pthread_create() - argument is function pointer

我的情况类似于another Question

我想传递一个函数作为参数和一个整数值。用简化的结构测试案例:

void print (int x, int y) 
{ cout << "x = " << x << ", y = " << y << endl; }

void *interrupt (struct arg_struct args);

struct arg_struct { 
    void (*func)(int,int);          // Argument 1
    int a;                          // Argument 2
    int b;                          // Argument 3
};  

int _tmain(int argc, _TCHAR* argv[]){ 

    int a = 1700, b = 1000;

    struct arg_struct arguments;

    arguments.func = print;
    arguments.a = a;
    arguments.b = b;

    (*interrupt)(arguments);

    cin.get(); return 0;
}


void *interrupt (struct arg_struct args) {

    void (*func) (int,int) ;

    func =  args.func;
    int x = args.a;
    int y = args.b;

    (*func)(x,y);

    return 0;           // Erfordert Rückgabewert
}

所以现在我想创建一个线程来执行这个传递的函数。

void *InThread_func(struct arg_struct *);   // Prototype                        

struct arg_struct { 
    void (*func)(int);          // Argument 1
    int IntNumber;              // Argument 2
};

int InThread(void (*func)(int), int IntNumber){
    
    struct arg_struct arguments;
    
    arguments.func   = func;
    arguments.IntNumber = IntNumber;

    // Initialize handler
    pthread_t InThread_thread;
    
    // Create thread
    pthread_create(&InThread_thread,NULL,&InThread_func,(void*) &arguments);
    
    pthread_join(InThread_func,NULL);

    return(errno);
}

正在使用

g++-4.6 -o test test.cpp

编译器说

invalid conversion from void* (*)(arg_struct*) to void * (*)(void*)

参考pthread_create的最后一个参数。

这是为什么?

C++ 在转换方面很挑剔。

void *InThread_func(struct arg_struct *);替换为void *InThread_func(void *my_data);,应该可以解决问题。

因为这是 C++,所以我建议使用 std::thread 那些对你可用。

"Why is that?" 因为您的转换无效 void* (*)( arg_struct* )void* (*)( void* ),也许吧。第三 pthread_create 的参数(不是最后一个) 必须 是一个 extern "C" void* (*)( void* )。 (有些编译器会忽略 extern "C" 的必要性。他们在这方面被打破了。)所以 你的 InThread_fnc (我在你的代码中找不到)一定是什么 喜欢:

extern "C" void*
InThread_fnc( void* from_pthread_create )
{
    arg_struct const* p = static_cast< arg_struct const* >( from_pthread_create );
    (*p->func)( p->IntNumber );
    return nullptr;
}

当然,只有当 pthread_create 的最后一个参数是 一个arg_struct*。这与您的情况相对应,但请注意 开始推导:传递 new Derived&someDerived 时 您开始强制转换为 Base* 的函数会导致未定义的行为。