gpt4 book ai didi

C++11 线程不适用于虚拟成员函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:00:55 26 4
gpt4 key购买 nike

我试图让一个类运行一个线程,该线程将在一个循环中调用一个名为 Tick() 的虚拟成员函数。然后我尝试派生一个类并覆盖 base::Tick()。

但是在执行的时候,程序只是调用了基类的Tick,而不是覆盖一个。有什么解决办法吗?

#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>

using namespace std;

class Runnable {
public:
Runnable() : running_(ATOMIC_VAR_INIT(false)) {

}
~Runnable() {
if (running_)
thread_.join();
}
void Stop() {
if (std::atomic_exchange(&running_, false))
thread_.join();
}
void Start() {
if (!std::atomic_exchange(&running_, true)) {
thread_ = std::thread(&Runnable::Thread, this);
}
}
virtual void Tick() {
cout << "parent" << endl;
};
std::atomic<bool> running_;

private:
std::thread thread_;
static void Thread(Runnable *self) {
while(self->running_) {
self->Tick();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
};

class Fn : public Runnable {
public:
void Tick() {
cout << "children" << endl;
}
};

int main (int argc, char const* argv[])
{
Fn fn;
fn.Start();
return 0;
}

输出:

parent

最佳答案

在您使用完一个对象之前,您不能让它超出范围! main 末尾的 return 0; 导致 fn 超出范围。因此,当您开始调用 tick 时,甚至无法保证该对象是否已经存在。

(~Runnable 中的逻辑完全被破坏了。在析构函数内部为时已晚——对象已经至少部分被销毁了。)

关于C++11 线程不适用于虚拟成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10634603/

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