Author Topic: creating a thread using a class member function  (Read 67308 times)

kkerbel

  • Newbie
  • *
  • Posts: 6
    • View Profile
creating a thread using a class member function
« on: July 30, 2012, 04:51:48 AM »
class a {
   void afunction(int a);
   ...
};

//this is obviously an incomplete class...just trying to make clear what I'm trying to do... :-)

how do I go about doing something like...

thread dosomething(afunction, 32);
dosomething.detach();

Anthony Williams

  • Administrator
  • Full Member
  • *****
  • Posts: 103
    • View Profile
    • just::thread C++ Thread Library
Re: creating a thread using a class member function
« Reply #1 on: July 30, 2012, 07:34:28 AM »
To create a thread using a class member function you need to pass a "this" pointer as the second parameter to the std::thread constructor:

Code: [Select]
a an_a_object;
std::thread dosomething(&a::afunction, &an_a_object,32); // a pointer to an a
std::thread t2(&a::function,std::ref(an_a_object),32); // a reference wrapped in std::ref
std::thread t3(&a::function,a(),32); // an rvalue, which is copied/moved into the thread storage

You might like to see my Multithreading in C++0x tutorial series. Member functions are covered in Part 3: Starting Threads with Member Functions and Reference Arguments

kkerbel

  • Newbie
  • *
  • Posts: 6
    • View Profile
Re: creating a thread using a class member function
« Reply #2 on: July 31, 2012, 04:28:10 AM »
As always...thanks!   :)