但是我不能访问非静态 成员“值”了。
那是因为在你的类static
功能没有(和不能有)this
指针。所有你需要的指针传递给Test
对象pthread_create()功能第四参数,然后做到这一点:
static void* thread_func(void* args)
{
Test *test = static_cast<Test*>(args);
test->value++;
//write return statement properly
}
但是,如果你正在做的thread_func()
太多的事情需要访问在很多地方Test
类的成员,那么我建议这样的设计:
//this design simplifies the syntax to access the class members!
class Test
{
//code omitted for brevity
static void* thread_func(void* args)
{
Test *test = static_cast<Test*>(args);
test->run(); //call the member function!
//write return statement properly
}
void run() //define a member function to run the thread!
{
value++;//now you can do this, because it is same as 'this->value++;
//you do have 'this' pointer here, as usual;
//so access other members like 'value++'.
}
//code omitted for brevity
}
更好的设计:定义一个可重用的类!
甚至更好的是定义与纯虚拟函数run()
一个可重复使用的类由派生类来实现。这是它应该如何设计:
//runnable is reusable class. All thread classes must derive from it!
class runnable
{
public:
virtual ~runnable() {}
static void run_thread(void *args)
{
runnable *prunnable = static_cast<runnable*>(args);
prunnable->run();
}
protected:
virtual void run() = 0; //derived class must implement this!
};
class Test : public runnable //derived from runnable!
{
public:
void newthread()
{
//note &runnable::run_thread
pthread_create(&runnable::run_thread,..., this);
}
protected:
void run() //implementing the virtual function!
{
value++; // your thread function!
}
}
看起来更好?
我已更新我的帖子。一探究竟! – Nawaz 2011-01-09 00:18:56