0

Possible Duplicate:
Start thread with member function

While defining a thread constructor with class method in c++0x as shown below, i get function cannot be resolved. What am i doing wrong?

For example, if i have

#include <thread>
 using namespace std;
class A
{
 public:
    void doSomething();
    A();
}

Then in Class A's constructor, i want to start a thread with doSomething. If i write like below, i get error that doSomething is not resolved. I even this->doSomething.

 A::A()
 {
     thread t(doSomething);
  }
Community
  • 1
  • 1
Jimm
  • 8,165
  • 16
  • 69
  • 118

1 Answers1

4

Try this:

class A
{
 public:
   void doSomething();

   A()
   {
      thread t(&A::doSomething, this);
    }
};

OR

class A
{
 public:
   static void doSomething();

   A()
   {
      thread t(&A::doSomething);
    }
};

Note: you need to join your thread somewhere, for example:

class A
{
public:
   void doSomething()
   {
      std::cout << "output from doSomething" << std::endl;
   }

   A(): t(&A::doSomething, this)
   {
   }
   ~A()
   {
     if(t.joinable())
     {
        t.join();
     }
   }

private:
  std::thread t;  
};

int main() 
{
    A a;        
    return 0;
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
billz
  • 44,644
  • 9
  • 83
  • 100