gpt4 book ai didi

c++ - 在线程中调用纯虚方法

转载 作者:行者123 更新时间:2023-11-28 01:45:19 26 4
gpt4 key购买 nike

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

#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();
}

但它失败并显示消息

terminate called without an active exception

pure virtual method called

消息“调用纯虚方法”只出现在一些失败消息中。我究竟做错了什么?是否与 Bar 或线程被不当销毁有关?

最佳答案

正如 Igor 在他的评论中指出的那样,您有一场数据竞赛。该线程实际上是在 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)) 在不同的地方。

关于c++ - 在线程中调用纯虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45395688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com