我有一些代码,其中打算在单独线程中执行的对象派生自具有纯虚拟Run函数的基类。我无法获得以下代码(简化的测试代码)来运行新线程。
#include <iostream>
#include <thread>
#include <functional>
class Base {
public:
virtual void Run() = 0;
void operator()() { Run(); }
};
class Derived : public Base {
public:
void Run() { std::cout << "Hello" << std::endl; }
};
void ThreadTest(Base& aBase) {
std::thread t(std::ref(aBase));
t.join();
}
int main(/*blah*/) {
Base* b = new Derived();
ThreadTest(*b);
}代码编译得很好(这是成功的一半),但是"Hello“永远不会打印出来。如果我做错了什么,我可能会在某个时刻出现运行时错误。我用的是gcc。
编辑:上面的代码无法在VS2012上编译,原因是:error C2064: term does not evaluate to a function taking 0 arguments
您需要使用lambda而不是std::ref,即
void ThreadTest(Base& aBase)
{
std::thread t([&] ()
{
aBase.Run();
});
t.join();
}发布于 2013-01-31 02:07:48
您需要将-pthread添加到g++命令行,如下面对一个类似问题的回答中所述:https://stackoverflow.com/a/6485728/39622。
https://stackoverflow.com/questions/14610224
复制相似问题