在c++编译环境下编译pthread_create会报错,出现问题的主要原因就是pthread_create的第3个参数——void*(void*)这个回调函数。
下面给出解决方法:
将要调用的函数改成静态函数或全局函数:
#include <iostream> using namespace std; #include <pthread.h>
void *Bar(void *arg) { cout << __PRETTY_FUNCTION__ << endl; } class Foo { public: Foo(); ~Foo(); static void * Bar(void *arg); private: pthread_t tid_self; pthread_t tid_other; }; Foo::Foo() { pthread_create(&tid_self, NULL, &Bar, NULL); pthread_join(tid_self, NULL); pthread_create(&tid_other, NULL, &::Bar, NULL); } Foo::~Foo() { pthread_join(tid_other, NULL); } void * Foo::Bar(void *arg) { cout << __PRETTY_FUNCTION__ << endl; } int main(int argc, char *argv[]) { Foo foo; return 0; }
若要调用类的成员,则用如下方法:
将传递的参数定义为struct:
struct myarg{ //其他参数 Foo* pFoo; }
然后在函数调用中:
void*Foo::Bar(void*arg) { struct myarg* parg = (struct myarg*) arg; Foo* pFoo = parg->pFoo; //下面就可以调用Foo的成员变量了 }