c++ - std::thread 成员函数。这个指针应该访问类字段吗?

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

最佳答案

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

关于c++ - std::thread 成员函数。这个指针应该访问类字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38144297/

相关文章:

c++ - 有没有类似 pthread_create 的 std::thread_create?

c++ - 我可以将 `std::this_thread::sleep_for()` 用于 MPI 进程吗?

c++ - 本地对象的范围

c++ - 错误 C3861 : 'cropImage' *: identifier not found

c++ - HTTP 输入流类 (C++)

c++ - C++ 程序和 cmd 控制台之间的管道

c++ - 分离线程访问全局或静态对象

c++ - 在类的外部定义时,模板 C++ 类中的 typedef 不起作用?

c++ - 在加载了 dlopen 的库中使用 std::thread 会导致 sigsegv