具有重载成员函数的多线程

时间:2014-10-03 12:44:50

标签: c++ multithreading c++11 syntax-error

使用

进行编译
$ g++ -std=c++0x -I "inc" src/*.cpp

并接收

src/ProcessGroup.cpp:25:10: error: no matching constructor for initialization of 'std::__1::thread'
  thread t(&Process::Run, p, exit_code);
         ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:349:9: note: candidate template
      ignored: couldn't infer template argument '_Fp'
thread::thread(_Fp&& __f, _Args&&... __args)
        ^

g++抱怨它找不到我给它的参数的匹配构造函数:

void
ProcessGroup::Add(Process *p)
{
  Process::status_t *exit_code = new Process::status_t;
  thread t(&Process::Run, p, exit_code);
  instance_t *instance = new instance_t(&p, &t);
  threads.insert(pair<instance_t*, Process::status_t*> (instance, exit_code));
}

// FIXME: Should *not* be using system(); this was just a standup to
// test multithreading
Process::status_t
Process::Run() const
{
  return system(command.c_str());
}

void
Process::Run(Process::status_t &exit_code)
{
  exit_code = Run();
}

据我所知,我要求编译器提供匹配

的构造函数
thread( <some function>, <some object>, <some argument>... )

哪个应该根据this answerStart thread with member function工作。它没有,所以很明显一定是错的,但是它是什么?

整个代码可在GitHub上找到。我向将来看这篇文章的人道歉 - 该存储库的历史可能会被重写。

1 个答案:

答案 0 :(得分:3)

你想:

std::thread t(static_cast<void(Process::*)(Process::status_t&)>(&Process::Run),
              p, std::ref(*exit_code));

由于您的成员函数已重载,因此您需要明确指定所需的重载。还要注意引用:std::thread 拥有所有绑定状态的对象,因此必须使外部状态的引用语义显式化。 当然,您需要取消引用指针exit_code