Search code examples
c++stdthread

std::thread member function. Should class fields be accessed by this pointer?


Given a class such as:

class MyClass {
  private:
  vector<std::string> data;

  void threadWork(std::vector<std::string> *data_ptr) {
    // some thread work... e.g
    for(int i=0; i < data_ptr->size(); i++) {
       std::string next = (*data_ptr)[i];
       // do stuff
    }
  }

  void callThreadedFunc(int nthread) {
    std::vector<std::thread> tgroup;
    std::vector<std::string> data_ptr = &data;
    for(int i=0; i < nthreads; i++) {
     tgroup.push_back(std::thread(&myClass::threadWork, this, data_ptr));
    }
    for(auto &t : tgroup) {t.join();}
  }
}

thisis required to be passed into the thread constructor. Does this mean I should be accessing all class fields that thread requires via this instead of by field specific pointers? For example, threadWork() should access data as follows:

void threadWork(MyClass *obj) {
// some thread work... e.g
  for(int i=0; i < obj->data.size(); i++) {
     std::string next = obj.data[i];
     // do stuff
  }
}

Solution

  • Since threadWork is a member function and you properly create the thread using this, you can access all member variables of the instance normally, no need to pass a pointer or reference to the data.

    Doing just

    std::thread(&myClass::threadWork, this)
    

    is enough, and then in the thread function you can use the member variables normally:

    void threadWork(/* no argument */) {
        // some thread work... e.g
        for(int i=0; i < data.size(); i++) {
            std::string next = data[i];  // Uses the member variable "normally"
           // do stuff
        }
    }