使用具有纯虚拟线程函数的 C++11 线程
Using C++11 thread with pure virtual thread function
我有代码,其中打算在单独线程中执行的对象派生自具有纯虚拟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();
}
您需要将 -pthread 添加到 g++ 命令行,如本回答中对类似问题的解释:https://stackoverflow.com/a/6485728/39622。
相关文章:
- C++使用params创建线程函数会导致转换错误
- 如何在大函数中编写多线程函数?
- C++11:将矢量元素作为线程传递到线程函数中
- 线程函数中的c++参数更改
- 我需要线程函数在不停止实际程序的情况下,每2秒打印一次随机数
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- 将项目插入 CTreeCtrl 时线程函数的奇怪行为
- C++ 线程函数通过引用传递
- 线程函数参数的前向声明不起作用
- 线程函数无法从堆上分配的缓冲区中读取字符
- 线程函数不打印
- C :如何在复杂模板类中指定线程函数
- 为什么我在C++线程函数调用中得到重复值?
- C++ 线程函数指针实现返回错误无效使用非静态成员函数
- 线程函数中的通用引用
- 如何同时启动两个具有不同线程函数的线程团队
- std::c++ 中的线程在设置线程函数时不会出错
- 对抽象类的引用不能传递给线程函数?
- 如何将ifstream作为参数传递给std ::线程函数
- 如何线程函数