我試圖讓一個類運行一個線程,它將在循環中調用名爲Tick()的虛擬成員函數。然後我試着派生一個類並覆蓋base :: Tick()。C++ 11線程不能使用虛擬成員函數
但是當執行時,程序只調用基類的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
就我個人而言,我認爲解決這個問題並不是最好的解決方案。我認爲最好的解決方案是首先不要造成這個問題。對於非問題來說,這是一個糟糕的解決方案。 –
不要用C++編寫Java。 –
你說得對。我爲捕捉系統做了這個工作,它會以恆定的頻率查詢一些源,例如10次/秒,並將數據提取到隊列中。並且有一個監視器將以另一個恆定頻率從隊列中拉出並顯示數據。因此,這是我想出的解決方案,創建一個基類,然後使用向量/列表來保存所有的源和監視器(而源可以在運行時添加/刪除)。有更好的解決方案 – xiaoyi