[英]C++11 threads in class
i am using the c++11 thread library with classes, and it works fine. 我正在使用带有类的c ++ 11线程库,并且工作正常。
I just need an explanation for this code so i understand it correctly. 我只需要对此代码的解释,以便我正确理解。
My class.h 我的课
class foo {
private:
std::thread t1;
void worker();
public:
void work();
};
the class.cpp class.cpp
#include "class.h"
void foo::worker() {
std::cout << "worker..." << std::endl;
}
void foo::work() {
t1 = std::thread(&foo::worker, this);
t1.join();
}
and now the main.cpp 现在是main.cpp
#include "class.h"
int main(int argc, char **argv) {
foo bar;
bar.work();
}
What I don't really understand is the invocation of the class-function for the thread. 我不太了解的是线程的类函数的调用。
I use std::thread(&foo::work, this)
and interpret this call as follows: The first parameter is the pointer to the function, but i dont know why i cant just call it without the &foo::
part. 我使用
std::thread(&foo::work, this)
并按如下方式解释此调用:第一个参数是指向该函数的指针,但我不知道为什么我不能不使用&foo::
部分就调用它。 The second parameter is the class itself that the thread knows the parent process? 第二个参数是线程本身知道父进程的类本身吗?
I couldn't find a explaination for this. 我找不到对此的解释。 Only the code and i would like to understand it.
只有代码,我想了解它。 Thanks!
谢谢!
&foo::work
is required because work
is a member function that belongs to class foo
. &foo::work
是必需的,因为work
是属于foo
类的成员函数。 A (non-static) member function can only be accessed if also the object it belongs to is known. (非静态)成员函数只能在已知其所属对象的情况下才能访问。
The this
parameter is a pointer to the object of which the method should be called. this
参数是一个指向应调用该方法的对象的指针。
The address bit is just the syntax for expressing the address of a member function. 地址位只是表示成员函数地址的语法。 I believe this could also be expressed as
this->worker
. 我相信这也可以表示为
this->worker
。 I don't know why worker
by itself is not allowed---it seems unambiguous, but that's C++. 我不知道为什么为什么不允许
worker
本身--看起来很明确,但这就是C ++。
You have to pass both the member function pointer and this
so that the thread can invoke the member function on the correct object. 您必须同时传递成员函数指针和
this
以便线程可以在正确的对象上调用成员函数。 Internally the thread holds a member function pointer, say pmf
(pointing to foo::worker
), and the object pointer, say po
(pointing to the this
that was passed). 在内部,线程拥有一个成员函数指针,例如
pmf
(指向foo::worker
),以及一个对象指针,例如po
(指向所传递的this
)。 It needs to be able to invoke (po->*pmf)()
, which result in worker
being invoked on the correct object. 它需要能够调用
(po->*pmf)()
,从而导致在正确的对象上调用worker
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.