Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 threads in class

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!

like image 916
baam Avatar asked Sep 03 '13 12:09

baam


2 Answers

&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.

like image 157
Appleshell Avatar answered Sep 21 '22 06:09

Appleshell


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.

like image 31
sfjac Avatar answered Sep 20 '22 06:09

sfjac