C ++ 11线程不能与虚拟成员函数一起工作 [英] C++11 thread doesn't work with virtual member function

查看:162
本文介绍了C ++ 11线程不能与虚拟成员函数一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个类运行一个线程,这将调用一个名为Tick()的虚拟成员函数在循环中。然后我试图派生一个类,并重写基类:: Tick()。

I'm trying to get a class run a thread, which will call a virtual member function named Tick() in a loop. Then I tried to derive a class and override the base::Tick().

但是当执行时,程序只是调用基类的Tick而不是覆盖一个。任何解决方案?

but when execute, the program just call the base class's Tick instead of override one. any solutions?

#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 的时候,不能保证对象已经存在了。

You can't let an object run out of scope until you're finished using it! The return 0; at the end of main causes fn to go out of scope. So by the time you get around to calling tick, there's no guarantee the object even exists any more.

〜Runnable 中的逻辑是完全破坏的,在析构函数里面太晚了 - 对象已经至少部分被破坏了。)

(The logic in ~Runnable is totally broken. Inside the destructor is way too late -- the object is already at least partially destroyed.)

这篇关于C ++ 11线程不能与虚拟成员函数一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆