静态线程函数访问非静态类成员在C ++中 [英] static thread function access non-static class member in C++
问题描述
Class Test{
int value;
static void* thread_func(void* args){
value++;
}
void newthread(){
pthread_create(&thread_func,...);
}
}
我试图在 Class Test。
因此编译器强迫我使 thread_func
static。但是,我不能访问非静态成员 value
。它说:
I'm trying to create a thread in Class Test.
Therefore compiler forces me to make thread_func
static. However I cannot access the non-static member "value
" anymore. It says:
invalid use of member 'Class::value' in static member function
有办法吗?
推荐答案
但是我不能访问非静态
成员
However I cannot access the non-static member "value" anymore.
这是因为你的类中的 static
无法具有)此
指针。您需要将指向 Test
的指针传递给 pthread_create()函数作为第四个参数,然后执行:
That is because static
function in your class doesn't have (and cannot have ) this
pointer. All you need to pass the pointer to your Test
object to pthread_create() function as fourth argument, and then do this:
static void* thread_func(void* args)
{
Test *test = static_cast<Test*>(args);
test->value++;
//write return statement properly
}
但是,如果你在 thread_func()
中需要访问 Test
类成员在许多地方,那么我建议这样的设计:
However, if you're doing too many things in thread_func()
that require access to Test
class members at many places, then I would suggest this design:
//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()
由派生类实现。下面是它应该如何设计:
Better design : define a reusable class!
Even better would be to define a reusable class with pure virtual function run()
to be implemented by the derived classes. Here is how it should be designed:
//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!
}
}
看起来更好?
这篇关于静态线程函数访问非静态类成员在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!