【问题标题】:c++ multithreading class methodsc++多线程类方法
【发布时间】:2013-05-28 08:48:11
【问题描述】:

我有以下问题。

vector<thread> vThreads;

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

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

我想将方法​​ findPath 传递给一个线程,但是我得到了很多错误...

> 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

我已经尝试过传递本地函数并且没有问题...

添加了 CRob 标头

#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();
};

【问题讨论】:

  • Crob的定义是什么?
  • 您应该使用std::bind() 将此方法传递给线程。

标签: c++ multithreading class methods


【解决方案1】:

看起来您正在尝试将非静态方法传递给 std::thread 构造函数。你不能这样做:非静态方法需要一个对象才能被调用。看起来像你想要的:

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

【讨论】:

  • 啊,非常感谢!但是我如何从我的列表中获得确切的对象?还是我用 i 得到它?我仍然得到一个错误... labrob.cpp: In function 'int main(int, char*)': labrob.cpp:72:35: error: invalid use of non-static member function 'virtual void Crob::findPath()' make: *** [labrob.o] 错误 1
  • 抱歉我忘记调用构造函数了
猜你喜欢
  • 1970-01-01
  • 2017-01-16
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-13
  • 1970-01-01
  • 2011-07-06
相关资源
最近更新 更多