std :: thread成员函数。该指针应该访问类字段吗?

时间:2016-07-01 11:27:53

标签: c++ stdthread

给出如下课程:

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而不是字段特定指针访问线程所需的所有类字段? 例如,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
  }
}

1 个答案:

答案 0 :(得分:3)

由于threadWork是一个成员函数,并且您使用this正确创建了该线程,因此您可以正常访问该实例的所有成员变量,无需传递指针或对数据的引用。 / p>

只做

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