Class Test{
int value;
static void* thread_func(void* args){
value++;
}
void newthread(){
pthread_create(&thread_func,...);
}
}
我正在尝试在Class Test.
中创建一个线程因此编译器强制我使thread_func
静态。但是我不能再访问非静态成员“value
”了。它说:
invalid use of member 'Class::value' in static member function
周围有办法吗?
答案 0 :(得分:14)
但是我无法访问非静态 会员“价值”了。
这是因为您班级中的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
}
更好的方法是使用 pure 虚拟函数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!
}
}
看起来更好?
答案 1 :(得分:1)
让thread_func将指向类对象的指针作为参数。
static void* thread_func(void* pThis)
{
static_cast<Test*>(pThis)->value++;
}
如果这种方法也想要获取其他信息,请将它们放在另一个struct/class
中并传入。