user2443761
user2443761

Reputation: 5

c++ multithreading class methods

I have following problem.

vector<thread> vThreads;

list<Crob *> lRobs;
list<Crob *>::iterator i;

for(i = lRobs.begin(); i != lRobs.end(); i++)
{
    vThreads.push_back(thread((*i)->findPath));
}

I want to pass the method findPath to a thread, but I just get a lot of errors...

> labrob.cpp: In function ‘int main(int, char**)’:
labrob.cpp:72:43: error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>)’
labrob.cpp:72:43: note: candidates are:
In file included from labrob.cpp:14:0:
/usr/include/c++/4.7/thread:131:7: note: std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int (Crob::*)(); _Args = {}]
/usr/include/c++/4.7/thread:131:7: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘int (Crob::*&&)()’
/usr/include/c++/4.7/thread:126:5: note: std::thread::thread(std::thread&&)
/usr/include/c++/4.7/thread:126:5: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘std::thread&&’
/usr/include/c++/4.7/thread:122:5: note: std::thread::thread()
/usr/include/c++/4.7/thread:122:5: note:   candidate expects 0 arguments, 1 provided
make: *** [labrob.o] Error 1

I have already tried to pass local functions and that worked without problems...

Added CRob header

#pragma once
#include "point.hpp"
#include "lab.hpp"

class Crob
{
  protected:
   Cpoint *pos;
   int steps;
   Clab *labfind;
   string direction;

  public:
   Crob(Clab *lab);
   virtual ~Crob();
   virtual void findPath(); 
   void moveTo(int x, int y);   
   void moveToPrint(int x, int y);  
   int getSteps(void);
   void checkDirection();
};

Upvotes: 0

Views: 912

Answers (1)

Guillaume
Guillaume

Reputation: 2054

Looks like you're trying to pass a non-static method to the std::thread constructor. You cannot do that: a non-static methods needs a object so it can be called. Looks like you want:

for(i = lRobs.begin(); i != lRobs.end(); i++)
{
    vThreads.push_back(std::thread(&Crob::findPath, *i));
}

Upvotes: 1

Related Questions