使用具有纯虚拟线程函数的 C++11 线程

Using C++11 thread with pure virtual thread function

本文关键字:线程 函数 C++11 虚拟      更新时间:2023-10-16

我有代码,其中打算在单独线程中执行的对象派生自具有纯虚拟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。