gpt4 book ai didi

c++ - 静态线程函数访问 C++ 中的非静态类成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:01:19 26 4
gpt4 key购买 nike

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

有办法解决吗?

最佳答案

However I cannot access the non-static member "value" anymore.

那是因为你的类中的 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!
}
}

看起来更好?

关于c++ - 静态线程函数访问 C++ 中的非静态类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4633222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com