2013-03-01 59 views
1

我正在写pthreads的类,它的头文件和.cpp定义文件。pthread运行功能私人类

在.hi有:

class test 
{ 
    public: 
     int a; 
    ... 
    private: 
     typedef void (*myfunc)(void *p); 
     static myfunc pthreadRun; 
} 

在的.cpp我有:

... 
typedef void (*myfunc)(void *p); 
myfunc test::pthreadRun 
{ 
    this->a = 10; 
    pthread_exit(NULL); 
} 
... 

我得到一个错误:void (* test::pthreadRun)(void*)不是class test静态成员,和一堆其他错误也是,但这是第一个。

我很困惑,因为它是静态的:/

pthreadRunpthread_create()

我缺少的是线程运行功能?

+2

Look [here](http://stackoverflow.com/questions/1151582/pthread-function-from-a-class)。你可以不要使用私有方法,至少不要这样... – 2013-03-01 10:48:57

+1

你不能用typedef声明一个函数。 – 2013-03-01 10:53:56

回答

1

很难猜测正是你正在尝试做的,但下手,我想我会重写你的代码是这样的:

class test 
{ 
    public: 
     int a; 
    ... 
    private: 
     static void pthreadRun(void *p); 
} 

void test::pthreadRun(void *p) 
{ 
    // this->a = 10; This line is now a big problem for you. 
    pthread_exit(NULL); 
} 

所以这是一种你正在寻找的结构,尽管你不能从这个上下文访问成员元素(比如this-> a),因为它是一个静态函数。

一般的方法之一处理,这是通过启动线程与此指针,以便在功能,您可以:

void test::pthreadRun(void *p) 
{ 
    test thistest=(test)p; 
    thistest->a=10; //what you wanted 
    thistest->pthreadRun_memberfunction(); //a wrapped function that can be a member function 
    pthread_exit(NULL); 
} 

你应该能够使所有这些功能的私有/保护(假设你开始从这个班级的线程,我认为这可能是最好的做到这一点。