21

I am trying to spawn a thread from within my class and the thread executes a particular method in my class. The code looks like this:

class ThreadClass{
    int myThread(int arg){
     // do something
    }

    void createThread(){
        thread t = thread(myThread,10);
    }

} ;

This code on compilation throws an error saying

std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int (ThreadClass::*)(int), _Args = {int}]
no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘int (ThreadClass::*&&)(int)’

I am not sure what is the actual bug here. Can someone help me with this?

Thanks.

Bach
  • 6,145
  • 7
  • 36
  • 61
CPS
  • 677
  • 2
  • 6
  • 9

1 Answers1

28

The problem is that a member function can't be called without an object. Provide a pointer to this so that the current object is used:

thread t(&ThreadClass::myThread, this, 10);

You could use an instance of any ThreadClass object, but in your case, it seems this is the right thing to do.

NOTE: Remember you need a reference to the created thread so that you can do a join() later on.

imreal
  • 10,178
  • 2
  • 32
  • 48
  • You need a reference to the created thread if you need to do a join() later on. – Martin James Dec 15 '12 at 09:37
  • I'm sorry, but which thread overload is this? – nore Jun 04 '23 at 19:38
  • @nore This one: `template< class Function, class... Args > explicit thread( Function&& f, Args&&... args );`. You can see it here: https://en.cppreference.com/w/cpp/thread/thread/thread – imreal Jun 14 '23 at 18:50
  • O.K., overload 3; but why is this `this` supplied? Isn't that recognized as an argument? – nore Jun 15 '23 at 19:03
  • 1
    @nore When calling a member function it is necessary to provide a `this` object. `std::invoke` (the mechanism used to start the thread) uses the first parameter as a `this` for the invocation. – imreal Jun 20 '23 at 15:07
  • I don't see any mention of this behavior on the reference page--thank you anyways. – nore Jun 22 '23 at 11:53