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

Wei*_*Shi 4 c++

Class Test{
    int value;
    static void* thread_func(void* args){
        value++;
    }
    void newthread(){
        pthread_create(&thread_func,...);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个线程Class Test.因此编译器强迫我创建thread_func静态.但是我不能再访问非静态成员了" value".它说:

invalid use of member 'Class::value' in static member function
Run Code Online (Sandbox Code Playgroud)

有办法解决吗?

Naw*_*waz 14

但是我不能再访问非静态成员"value"了.

那是因为static你的类中的函数没有(也没有)this指针.您需要将指向您的Test对象的指针传递给pthread_create()函数作为第四个参数,然后执行以下操作:

static void* thread_func(void* args)
{
      Test *test = static_cast<Test*>(args);
      test->value++;
      //write return statement properly
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你做了太多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 Code Online (Sandbox Code Playgroud)

更好的设计:定义可重用的类!


更好的方法是定义一个可重用的类,其中包含由派生类实现的虚函数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!
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来更好?