给定一个类,例如:
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/