std::thread 成员函数。 class 字段应该被这个指针访问吗?

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

给定一个 class 例如:

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();}
  }
}

this需要传入线程构造函数。这是否意味着我应该通过 this 访问线程所需的所有 class 字段,而不是通过特定于字段的指针? 例如,threadWork() 应该按如下方式访问 data

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
  }
}

由于threadWork是一个成员函数,你使用this正确创建线程,你可以正常访问实例的所有成员变量,不需要传递指针或对数据的引用.

正在做

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

就够了,然后在线程函数中就可以正常使用成员变量了:

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
    }
}