i am using the c++11 thread library with classes, and it works fine.
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
#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
#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.
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
. 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.
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
. I don't know why worker
by itself is not allowed---it seems unambiguous, but that's 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. 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). It needs to be able to invoke (po->*pmf)()
, which result in worker
being invoked on the correct object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With