C++ 如何从计算线程到GUI线程获取结果-我需要QSharedMemory吗?

C++ 如何从计算线程到GUI线程获取结果-我需要QSharedMemory吗?,c++,qt,C++,Qt,我需要两个线程(主线程(GUI)和计算线程)之间的共享接口。在启动期间,主线程将所有信号存储在QHash()中。第二个线程在每个计算步骤中写入键/值。我应该将它们存储在QSharedMemory中吗 我的应用程序有两个线程。GUI线程和计算线程。用户可以通过GUI以快速模式或实时模式启动模拟。计算随着时间的推移而演变模拟模型。它们的速度足够快,可以比实时更快地执行。如果插入延迟,它们可以保持实时速度,如在游戏或动画中 计算线程应在以下四种模式之一中执行计算: 快速模式:计算无延迟完成,模型演化速

我需要两个线程(主线程(GUI)和计算线程)之间的共享接口。在启动期间,主线程将所有信号存储在
QHash()
中。第二个线程在每个计算步骤中写入键/值。我应该将它们存储在
QSharedMemory
中吗

我的应用程序有两个线程。GUI线程和计算线程。用户可以通过GUI以快速模式或实时模式启动模拟。计算随着时间的推移而演变模拟模型。它们的速度足够快,可以比实时更快地执行。如果插入延迟,它们可以保持实时速度,如在游戏或动画中

计算线程应在以下四种模式之一中执行计算:

  • 快速模式:计算无延迟完成,模型演化速度快于实时。这是通过
    在线程运行中实现的,而(…){…run_ComputeFunction()…}

  • 实时模式:这是在线程运行时使用QTimer Timeout和slot
    run\u ComputeFunction()
    实现的

  • 单步模式:用户通过GUI启动每个时间步。这类似于调试器中的单步执行。这是在线程运行时以start Thread Thread THEN run\U ComputeFunction THEN wait条件实现的

  • 停止模式:停止计算


  • 为了以防万一您还没有遇到它,Qt提供了一个QSharedMemory示例,可以让您从正确的方向开始:

    QThread文档还将有助于:


    如果您仍然无法回答问题,您可以随时用最少的代码示例更新您的问题。

    为了防止您还没有遇到问题,Qt提供了一个QSharedMemory示例,可以让您从正确的方向开始:

    QThread文档还将有助于:

    如果您仍然被卡住,您可以随时用最少的代码示例更新您的问题。

    TL;医生:你没有

    我需要两个线程(主线程(GUI)和计算线程)之间的共享接口。(强调矿山)

    QSharedMemory
    仅适用于多处理,而不是多线程。线程的整体思想是,它们就像进程,但共享它们所在进程的所有内存

    因此,您的所有线程都可以看到进程可用的所有内存,您根本不需要做任何事情来共享它

    您需要确定计算线程是否应该:

  • 仅更新与主线程共享的数据结构,或

  • 通过提供已更改的键值对来通知主线程其状态的更改,或

  • 两者都有

  • 更新数据结构的问题在于,除非还提供更改通知,否则主线程将别无选择,只能轮询结构以进行更改。因此,现在您在主线程上运行一些代码,这些代码做的不多,但在计时器上运行,强制CPU唤醒,使您的移动和虚拟化用户讨厌您。不太好

    由于对共享数据结构的任何访问都必须受到互斥的保护,以便在写入程序更新值时,读卡器不会读到乱七八糟的内容,因此您可以在以下两种情况之间做出选择:

  • 在计算线程中只保留数据结构的一个副本,并在互斥保护下访问它。主线程和计算线程将竞争互斥,性能将受到影响

  • 保留数据结构的两个副本—一个在计算线程上,另一个在希望跟踪计算进度的任何线程中

  • 保留一个无锁数据结构的副本

  • 下面,我将演示如何在计算线程和主线程中保持单独的数据结构。我还利用模型视图和标准模型为计算引擎提供UI

    计算机的实现分为抽象基类和特定于计算问题的具体实现。一个具体类所需要做的就是实现两种方法:一种是计算一个模拟时间步,返回其长度,另一种是通知其用户数据的更改

    计算机
    对象为其数据提供随机更新,“模拟”随机持续时间的时间步。它通过睡眠1/4随机选择时间步长的持续时间来阻止随机时间量。因此,它的作用就好像它可以比实时计算数据快4倍

    AbstractComputer
    采用了这个简单的功能,并在此基础上提供了四种操作模式:单步、实时和快速

    根据模拟的时间推移,
    computeChunk
    在一个数据块中执行的计算量设置为
    m\u notifyPeriod
    ,此处设置为20ms

    在除
    停止
    以外的所有操作模式中,在将控制返回到事件循环之前,始终至少计算单个块,以保持计算线程的响应性。单个计时器用于将控制从事件循环返回到计算机,并安排未来的计算。在实时模式下,如果计算在实时时钟之前,则在适当的时间安排下一次计算,以便实时运行。在快速模式下,计时器设置为零超时,立即从事件循环返回控制以执行另一个计算块。这具有非常低的开销

    抽象计算机跟踪累计的模拟时间步(
    simTime

    计算机对象在其自己的线程中运行,并对其数据提供定期、随机生成的更新。数据更改通过通知信号指示。
    #include <QtWidgets>
    #include <random>
    
    class AbstractComputer : public QObject {
       Q_OBJECT
       Q_PROPERTY (Mode mode READ mode WRITE setMode NOTIFY modeChanged)
       Q_PROPERTY (double simTime READ simTime WRITE setSimTime
                   RESET resetSimTime NOTIFY simTimeChanged)
    public:
       enum Mode { Stop, Step, RealTime, Fast };
    protected:
       typedef double Time; ///< units of seconds
    
       /// Performs one computation step and returns the amount of time the simulation has
       /// been advanced by. The computation updates one or more parameters in the map, but
       /// doesn't signal the updates. The changed parameters are kept in set.
       /// This method can change m_mode to Stop to direct the calling code to stop/pause
       /// the simulation.
       virtual Time compute() = 0;
    
       /// Notifies of accumulated changes and clears the update set.
       virtual void notify() = 0 ;
    private:
       Mode m_mode, m_prevMode;
       QBasicTimer m_timer;
       QElapsedTimer m_timeBase;
       qint64 m_lastNotification; ///< Last m_timeBase at which notification was issued.
       Time m_notifyPeriod; ///< Real time period to issue data change notifications at.
       Time m_modeSimTime;  ///< Simulation time accumulated in current mode.
       Time m_simTime;      ///< Total simulation time.
    
       /// Computes a chunk of work that amounts to m_notifyPeriod in simulated time
       void computeChunk() {
          Time t = 0;
          do
             t += compute();
          while (m_mode != Stop && t < m_notifyPeriod);
          m_modeSimTime += t;
          m_simTime += t;
       }
    
       /// Runs computations according to the selected mode. In RealTime and Fast modes,
       /// the notifications are issued at least every m_notifyPeriod.
       void timerEvent(QTimerEvent * ev) {
          if (ev->timerId() != m_timer.timerId()) return;
          const Time startSimTime = m_simTime;
          const Mode startMode = m_mode;
          switch (m_mode) {
          case Step:
             m_simTime += compute();
             m_timer.stop();
             m_mode = Stop;
             break;
          case Stop:
             m_timer.stop();
             break;
          case RealTime:
             if (m_prevMode != RealTime) {
                m_modeSimTime = 0.0;
                m_timeBase.start();
             }
             computeChunk();
             if (m_mode == RealTime) {
                int ahead = round(m_modeSimTime * 1000.0 - m_timeBase.elapsed());
                if (ahead < 0) ahead = 0;
                m_timer.start(ahead, Qt::PreciseTimer, this);
             }
             break;
          case Fast:
             if (m_prevMode != Fast) {
                m_timeBase.start();
                m_lastNotification = 0;
             }
             do
                computeChunk();
             while (m_mode == Fast
                    && ((m_timeBase.elapsed() - m_lastNotification) < m_notifyPeriod*1000.0));
             m_lastNotification = m_timeBase.elapsed();
             break;
          }
          notify();
          if (startSimTime != m_simTime) emit simTimeChanged(m_simTime);
          if (m_prevMode != m_mode || startMode != m_mode) emit modeChanged(m_mode);
          m_prevMode = m_mode;
       }
    public:
       AbstractComputer(QObject * parent = 0) :
          QObject(parent), m_mode(Stop), m_prevMode(Stop), m_notifyPeriod(0.02) /* 50 Hz */,
          m_simTime(0.0)
       {}
       Q_SIGNAL void modeChanged(AbstractComputer::Mode mode); // fully qualified type is required by moc
       Q_SIGNAL void simTimeChanged(double);
       Q_SLOT void setMode(AbstractComputer::Mode mode) { // fully qualified type is required by moc
          if (m_mode == mode) return;
          m_mode = mode;
          if (m_mode != Stop) m_timer.start(0, this); else m_timer.stop();
       }
       Q_SLOT void stop() { setMode(Stop); }
       Mode mode() const { return m_mode; }
       double simTime() const { return m_simTime; }
       void setSimTime(double t) { if (m_simTime != t) { m_simTime = t; emit simTimeChanged(t); } }
       void resetSimTime() { setSimTime(0.0); }
    };
    Q_DECLARE_METATYPE(AbstractComputer::Mode)
    
    class Computer : public AbstractComputer {
       Q_OBJECT
    public:
       typedef QHash<QString, double> Map;
    private:
       typedef QSet<QString> Set;
       std::default_random_engine m_eng;
       Map m_data;
       Set m_updates;
    
       Time compute() Q_DECL_OVERRIDE {
          // Update one randomly selected parameter.
          auto n = std::uniform_int_distribution<int>(0, m_data.size()-1)(m_eng);
          auto it = m_data.begin();
          std::advance(it, n);
          auto val = std::normal_distribution<double>()(m_eng);
          *it = val;
          m_updates.insert(it.key());
          float tau = std::uniform_real_distribution<float>(0.001, 0.1)(m_eng);
          // Pretend that we run ~4x faster than real time
          QThread::usleep(tau*1E6/4.0);
          return tau;
       }
       void notify() Q_DECL_OVERRIDE {
          for (auto param : m_updates)
             emit valueChanged(param, m_data[param]);
          m_updates.clear();
       }
    public:
       Computer(const Map & data, QObject * parent = 0) :
          AbstractComputer(parent), m_data(data) {}
       Map data() const { return m_data; }
       Q_SIGNAL void valueChanged(const QString & key, double val);
    };
    
    class UI : public QWidget {
       Q_OBJECT
       QHash<QString, int> m_row;
       QStandardItemModel m_model;
       QFormLayout m_layout { this };
       QTableView m_view;
       QComboBox m_mode;
    public:
       UI(const Computer * computer, QWidget * parent = 0) :
          QWidget(parent),
          m_model(computer->data().size() + 1, 2, this)
       {
          auto data = computer->data();
          m_mode.addItem("Stop", Computer::Stop);
          m_mode.addItem("Step", Computer::Step);
          m_mode.addItem("Real Time", Computer::RealTime);
          m_mode.addItem("Fast", Computer::Fast);
          m_mode.setFocusPolicy(Qt::StrongFocus);
          m_view.setFocusPolicy(Qt::NoFocus);
          m_layout.addRow(&m_view);
          m_layout.addRow("Sim Mode", &m_mode);
          m_model.setItem(0, 0, new QStandardItem("Sim Time [s]"));
          m_model.setItem(0, 1, new QStandardItem);
          int row = 1;
          for (auto it = data.begin(); it != data.end(); ++it) {
             m_model.setItem(row, 0, new QStandardItem(it.key()));
             m_model.setItem(row, 1, new QStandardItem(QString::number(it.value())));
             m_row[it.key()] = row++;
          }
          newMode(computer->mode());
          newSimTime(computer->simTime());
          m_view.setModel(&m_model);
          connect(&m_mode, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
                  [this](int i){
             emit modeChanged((AbstractComputer::Mode)m_mode.itemData(i).toInt());
          });
       }
       Q_SIGNAL void modeChanged(AbstractComputer::Mode);
       Q_SLOT void newValue(const QString & key, double val) {
          m_model.item(m_row[key], 1)->setText(QString::number(val));
       }
       Q_SLOT void newSimTime(double t) {
          m_model.item(0, 1)->setText(QString::number(t));
       }
       Q_SLOT void newMode(AbstractComputer::Mode mode) {
          m_mode.setCurrentIndex(m_mode.findData(mode));
       }
    };
    
    struct Thread : public QThread { ~Thread() { quit(); wait(); } };
    
    int main(int argc, char *argv[])
    {
       QApplication a(argc, argv);
       qRegisterMetaType<AbstractComputer::Mode>();
       Computer::Map init;
       init.insert("Foo", 1);
       init.insert("Bar", 2);
       init.insert("Baz", 3);
       Computer computer(init);
       QScopedPointer<Thread> thread;
       UI ui(&computer);
       QObject::connect(&computer, &Computer::valueChanged, &ui, &UI::newValue);
       QObject::connect(&computer, &Computer::simTimeChanged, &ui, &UI::newSimTime);
       QObject::connect(&computer, &Computer::modeChanged, &ui, &UI::newMode);
       QObject::connect(&ui, &UI::modeChanged, &computer, &Computer::setMode);
       int threadCount = Thread::idealThreadCount();
       if (threadCount == -1 || threadCount > 1) { // Assume a multicore machine
          thread.reset(new Thread);
          computer.moveToThread(thread.data());
          thread->start();
          // Prevent the bogus "QBasicTimer::stop: Failed." warnings.
          QObject::connect(thread.data(), &QThread::finished, &computer, &Computer::stop);
       }
       ui.show();
       return a.exec();
    }
    
    #include "main.moc"