在线程中调用纯虚拟方法

Invoking a pure virtual method within a thread

本文关键字:虚拟 方法 调用 线程      更新时间:2023-10-16

当从基类方法中生成线程时,我需要调用纯虚拟方法实现,如下所示。

#include <iostream>
class Foo {
private:
std::thread tr;
public:
virtual void baz() = 0;
void foo() {
this->tr = std::thread([=] { this->baz(); });
}
};
class Bar : public Foo {
public:
void baz() {
std::cout << "In baz" << "n";
}
};

主类...

#include <thread>
#include "test.hpp"
int main(int argc, char* argv[]) {
Bar b;
b.foo();
}

但它失败并显示消息

终止调用而不显示活动异常

称为纯虚拟方法

消息"纯虚拟方法已调用"仅出现在某些失败消息中。我做错了什么?是否与 Bar 或线程被不当破坏有关?

正如伊戈尔在他的评论中指出的那样,你有一个数据竞赛。线程实际上是在Bar被销毁后执行的(当然,实际的执行顺序没有定义,所以有时你可能会很幸运(。为了防止这种情况,您需要在Bar被销毁之前tr.join();

class Foo {
std::thread tr;
protected:
void join() { tr.join(); }
public:
virtual ~Foo() = default;  // ~Foo should be virtual or protected, if Foo contains virtual methods
virtual void baz() = 0;
void foo() {
this->tr = std::thread([=] { this->baz(); });
}
};
class Bar : public Foo {
public:
~Bar() { join(); }
void baz() { std::cout << "In baz" << "n"; }
};

如果要对此进行更多研究,请在各种方法(尤其是析构函数(中添加一些cout,并在不同位置添加std::this_thread::sleep_for (std::chrono::seconds(1))