[英]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();}
}
}
this
is required to be passed into the thread constructor. this
需要传递给线程构造函数。 Does this mean I should be accessing all class fields that thread requires via this
instead of by field specific pointers? 这是否意味着我应该通过
this
而不是通过特定于字段的指针来访问线程需要的所有类字段? For example, threadWork()
should access data
as follows: 例如,
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
}
}
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. 由于
threadWork
是成员函数,并且您可以使用this
正确创建线程,因此您可以正常访问实例的所有成员变量,而无需传递指针或对数据的引用。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.